PHP设计模式之单例模式
单例模式就是确保一个类只有一个实例,并且是自行实例化。
三个要点:
1、保存唯一实例的静态成员变量;
2、构造函数私有化;
3、访问这个实例的公共的静态方法(通常为getInstance方法),返回唯一实例的一个引用
代码如下:
<?php class test{ private static $_instance; private $v=""; private function __construct(){ } static public function getinstance(){ if(!self::$_instance instanceof self){ self::$_instance = new self; } return self::$_instance; } public function set($s){ $this->v.=$s; } public function show(){ echo $this->v; } } ?>
测试是否同一个实例:
<?php require_once('danli.class.php'); $t=TEST::getinstance(); $t->set('hello world'); $t->show(); echo '<br>'; $t2=TEST::getinstance(); $t2->set('----hello world'); $t2->show(); ?>
输出结果为:
hello world
hello world----hello world
hello world----hello world
这段代码中,$t为该类的一个实例,通过set方法设置了test类的成员变量$v的值,然后输出hello world;$t2指向的也是同一个实例,为什么这么说?因为$t2也调用了test类的set方法,如果$t和$t2表示的不是同一个实例的话,那输出的结果应该是
hello world
----hello world
----hello world
但实际结果并不是这样,所以,流程应该是$t通过set方法设置了成员变量$v的值,此时$v=='hello world';然后$t2也调用了set方法设置了$v的值,因为他们是同一个实例,所以$v=='hello world----hello world'。
下面给个普通类的对比例子:
这是一个普通类:
<?php class test{ private $v=""; public function set($s){ $this->v.=$s; } public function show(){ echo $this->v; } } ?>
测试:
<?php require_once('putong.class.php'); $t=new test(); $t->set('hello world'); $t->show(); echo '<br>'; $t2=new test(); $t2->set('----hello world'); $t2->show(); ?>
输出结果为:
hello world
----hello world
----hello world
上面的这段代码test有两个实例$t,$t2,他们表示两个不同的实例,所以他们输出的内容各不相关,通过set方法设置了什么就输出什么。