您的位置:首页 > 编程语言 > PHP开发

php设计模式工厂模式及单例模式

2012-07-23 15:04 686 查看

工厂模式:

<?php
class Example
{
// The parameterized factory method
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception ('Driver not found');
}
}
}
?>


单例设计模式程序:

final class SuperMan {

private static $self;

private $name;

/**
* 私有构造函数,防止随便创建
*2
* @param string $name:
*/
private function __construct(){
}
/**
* 召唤超人的唯一方法
*
* @return SuperMan
*/
static function call(){
if (!self::$self) {
self::$self=new SuperMan();
}
return self::$self;
}
/**
* 调试用方法
* @return string
*/
function getName(){
return $this->name;
}

function setName($name){
$this->name=$name;
}

/**
* 关闭复制
*
*/
function __clone(){
throw new Exception("超人不能克隆");
}

/**
* 关闭序列化
*
*/
function __sleep(){
throw new Exception("超人不能保存");
}

/**
* 关闭反序列化
*
*/
function __wakeup(){
throw new Exception("超人不能恢复");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息