设计模式学习

单例模式

主要针对数据库句柄连接数据库的行为,使用单例模式可以避免大量的new操作。是一种对全局变量的改进。


class User{
    private static $_instance = null; //静态变量保存实例
    private $name;
    private function __construct()
    {
    }
    private function __clone()
    {
        // TODO: Implement __clone() method.
    }
    static public function getInstance(){
        if(is_null(self::$_instance)){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

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



}

$oa = User::getInstance();
$ob = User::getInstance();
$oa->setName("111");
$ob->setName("222");
$oa->getName();
$ob->getName();

工厂模式

类中定义抽象一些方法,用以在子类中实现,方便子类拓展


class Factory{
    static public function fac($id){
        if($id == 1) return new A();
        else if($id == 2 )return  new B();
        else return new C();
    }


}

interface FetchName{
    public function getName();
}

class A implements FetchName {
    private $name = "AA";
    public function getName()
    {
        // TODO: Implement getName() method.
        echo $this->name;
    }
}
class B implements FetchName {
    private $name = "BB";
    public function getName()
    {
        // TODO: Implement getName() method.
        echo $this->name;
    }
}
class C implements FetchName {
    private $name = "CC";
    public function getName()
    {
        // TODO: Implement getName() method.
        echo $this->name;
    }
}


$oa = Factory::fac(1);
if($oa instanceof FetchName) $oa->getName();*/