php开发模式

单例模式

  1. 防止频繁的new操作占用资源

  2. 是对全局变量的一种改进

  3. 代码示例

     <?php
     final class User
     {
         private static $_obj = null;
    
         private function __construct()
         {
             echo "首次执行构造函数。\n";
         }
    
         //单例统一访问入口
         public static function getObj() {
             if(!(self::$_obj instanceof self)){
                 echo "首次执行实例化对象。\n";
                 self::$_obj = new self;
             }
             return self::$_obj;
         }
    
         public function sayHello($name) {
             return "你好{$name}。\n";
         }
     }
    
     $user_1 = User::getObj();
     echo $user_1->sayHello('张三');
    
     $user_2 = User::getObj();
     echo $user_2->sayHello('李四');
    
     $user_3 = User::getObj();
     echo $user_3->sayHello('王五');
    

工厂模式

  1. 多个类(class)实现(implements)一个接口(interface),可以通过工厂类创建某个类的一个对象,而非直接new

  2. 代码示例

     <?php
     //定义一个接口
     interface Inter
     {
         public function getName();
     }
    
     //接口实现1
     class Class1 implements Inter
     {
         private $name = "张三";
         public function getName()
         {
             return $this->name;
         }
     }
    
     //接口实现2
     class Class2 implements Inter
     {
         private $name = "李四";
         public function getName()
         {
             return $this->name;
         }
     }
    
     //接口实现3
     class Class3 implements Inter
     {
         private $name = "王五";
         public function getName()
         {
             return $this->name;
         }
     }
    
     //接口实现4
     class Class4 implements Inter
     {
         private $name = "赵六";
         public function getName()
         {
             return $this->name;
         }
     }
    
     //定义一个工厂类
     class Factory
     {
         public static function chouse($chouse)
         {
             if($chouse == 1){
                 return new Class1();
             }elseif($chouse == 2){
                 return new Class2();
             }elseif($chouse == 3){
                 return new Class3();
             }
             return new Class4();
         }
     }
     ?>
    
  3. 工厂类使用

     //选择实例化类Class2
     $c = Factory::chouse(2);
    
     //判断$c是否实现了接口Inter
     if($c instanceof Inter){
         echo $c->getName();
     }
    
@耿志环 2012-∞ 冀ICP备17033181号, powered by Gitbook修订: 2018-05-23 16:25:59

results matching ""

    No results matching ""