工厂模式:
<?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("超人不能恢复"); } }