PHP设计模式之工厂模式与单例模式

2025-05-29 0 105

本文实例讲述了PHP设计模式工厂模式单例模式实现方法。分享给大家供大家参考,具体如下:

设计模式简单说应对某类问题而设计的解决方式

工厂模式应对需求创建相应的对象

?

1

2

3

4

5

6

7

8

9
class factory{

function __construct($name){

if(file_exists('./'.$name.'.class.php')){

return new $name;

}else{

die('not exist');

}

}

}

单例模式只创建一个对象的实例,不允许再创建实例,节约资源(例如数据库的连接)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
class instance{

public $val = 10;

private static $instance ;

private function __construct(){}

private function __clone(){}

//设置为静态方法才可被类调用

public static function getInstance(){

/*if(!isset(self::$instance)){

self::$instance = new self;

}*/

if(!isset(instance::$instance)){

instance::$instance = new self;

}

return instance::$instance;

}

}

$obj_one = instance::getInstance();

$obj_one->val = 20;

//clone可以调用__clone()克隆即new出一个新的的对象

//$obj_two = clone $obj_one;

$obj_two = instance::getInstance();

echo $obj_two->val;

echo '<p>';

var_dump($obj_one,$obj_two);

运行结果如下:

?

1

2

3

4

5
20

object(instance)[1]

public 'val' => int 20

object(instance)[1]

public 'val' => int 20

应用:数据库连接类(database access oject)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54
class mysqldb{

private $arr = array(

'port' => 3306,

'host' => 'localhost',

'username' => 'root',

'passward' => 'root',

'dbname' => 'instance',

'charset' => 'utf8'

);

private $link;

static $instance;

private function __clone(){}

private function __construct(){

$this->link = mysql_connect($this->arr['host'],$this->arr['username'],$this->arr['passward']) or die(mysql_error());

mysql_select_db($this->arr['dbname']) or die('db error');

mysql_set_charset($this->arr['charset']);

}

static public function getInsance(){

if(!isset(mysqldb::$instance)){

mysqldb::$instance = new self;

}

return mysqldb::$instance;

}

public function query($sql){

if($res = mysql_query($sql)){

return $res;

}return false;

}

//fetch one

public function get_one($sql){

$res = $this->query($sql);

if($result = mysql_fetch_row($res)){

return $result[0];

}

}

//fetch row

public function get_row($sql){

$res = $this->query($sql);

if($result = mysql_fetch_assoc($res)){

return $result;

}

return false;

}

//fetch all

public function get_all($sql){

$res = $this->query($sql);

$arr = array();

while($result = mysql_fetch_assoc($res)){

$arr[] = $result;

}

return $arr;

}

}

$mysql = mysqldb::getInsance();

希望本文所述对大家PHP程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP设计模式之工厂模式与单例模式 https://www.kuaiidc.com/97069.html

相关文章

发表评论
暂无评论