单例模式:达到只有一个实例
代码如下:
<?php
class C{
private static $_instance;
private function __construct(){
}
public static function getInstance(){
if(!(self::$_instance instanceof self)){
self::$_instance = new self;
}
return self::$_instance;
}
}
$o = C::getInstance();
?>
工厂模式:专门用于生产对象
代码如下:
<?php
class C {
}
class Factory {
private static $instances;//保存所有的实例
public static function getInstance($class_name) {
$class_name = strtolower($class_name);//将所有的都转换成小写
if(!isset(self::$instances[$class_name])) {
self::$instances[$class_name] = new $class_name;
}
return self::$instances[$class_name];
}
}
$c1 = Factory::getInstance('C');
?>