php设计模式之单例模式的例子,供大家参考,具体内容如下
<?php
/**
* php设计模式 单例模式
*/
class fruit{
private static $instancemap = array();
//protected getter for singleton instances
protected static function getsingleton($classname){
//保证单例模式 并且不能从控制器实例化和克隆
if (!isset(self::$instancemap[$classname])) {
$object = new $classname;
//make sure this object inherit from singleton
if ($object instanceof fruit) {
self::$instancemap[$classname] = $object;
var_dump($object);
} else {
throw singletonexception("class '$classname' do not inherit from singleton!");
}
}
return self::$instancemap[$classname];
}
//protected constructor to prevent outside instantiation
protected function __construct(){}
//denie cloning of singleton objects
public final function __clone(){
trigger_error('it is impossible to clone singleton', e_user_error);
}
}
class apple extends fruit{
protected $rndid;
public function __construct(){
$this->rndid = rand();
}
public function whatami(){
echo 'i am a apple(' . $this->rndid . ')<br />';
}
public static function getinstance(){
//echo get_class();
return fruit::getsingleton(get_class());
}
}
class greenapple extends apple{
public function whatami(){
echo 'i am a greenapple(' . $this->rndid . ')<br />';
}
public static function getinstance(){
return fruit::getsingleton(get_class());
}
}
$apple1 = apple::getinstance();
//var_dump($apple1);
$apple2 = greenapple::getinstance();
$apple1->whatami();// should echo 'i am a apple(some number)
$apple2->whatami();// should echo 'i am a greenapple(some number)
$apple1 = apple::getinstance();
$apple2 = greenapple::getinstance();
//保证单例模式
$apple1->whatami();// should echo 'i am a apple(same number as above)
$apple2->whatami();// should echo 'i am a greenapple(same number as above)
// $a = clone $apple1;// this should fail
// $b = clone $apple2;// this should fail
以上就是本文的全部内容,希望对大家学习php程序设计有所帮助。
评论列表:
发布于 3天前回复该评论
发布于 3天前回复该评论
发布于 3天前回复该评论
发布于 2天前回复该评论
发布于 2天前回复该评论
发布于 2天前回复该评论
发布于 2天前回复该评论
发布于 1天前回复该评论