PHP - 设计模式

Microsoft设计模式理论是,"该文档引入模式,然后将它们呈现在存储库或目录中,其组织有助于找到解决问题的正确模式组合".

设计模式示例

Singleton

一个类有一个实例,它提供了一个全局访问点,下面的代码将解释关于单身概念.

<?php
   class Singleton {
      public static function getInstance() {
         static $instance = null;
         
         if (null === $instance) {
            $instance = new static();
         }
         return $instance;
      }
      protected function __construct() {
      }
      
      private function __clone() {
      }
      
      private function __wakeup() {
      }
   }
   
   class SingletonChild extends Singleton {
   }
   
   $obj = Singleton::getInstance();
   var_dump($obj === Singleton::getInstance());
   
   $anotherObj = SingletonChild::getInstance();
   var_dump($anotherObj === Singleton::getInstance());
   var_dump($anotherObj === SingletonChild::getInstance()); 
?>

基于静态方法创建实现的上述示例是getInstance()

Factory

A Class Simple创建对象并且您想要使用该对象,下面的示例将解释工厂设计模式.

<?php
   class Automobile {
      private $bikeMake;
      private $bikeModel;
      
      public function __construct($make, $model) {
         $this->bikeMake = $make;
         $this->bikeModel = $model;
      }
      
      public function getMakeAndModel() {
         return $this->bikeMake . ' ' . $this->bikeModel;
      }
   }
   
   class AutomobileFactory {
      public static function create($make, $model) {
         return new Automobile($make, $model);
      }
   }
   
   $pulsar = AutomobileFactory::create('ktm', 'Pulsar');
   print_r($pulsar->getMakeAndModel());
   
   class Automobile {
      private $bikeMake;
      private $bikeModel;
      
      public function __construct($make, $model) {
         $this->bikeMake = $make;
         $this->bikeModel = $model;
      }
      
      public function getMakeAndModel() {
         return $this->bikeMake . ' ' . $this->bikeModel;
      }
   }
   
   class AutomobileFactory {
      public static function create($make, $model) {
         return new Automobile($make, $model);
      }
   }
   t$pulsar = AutomobileFactory::create('ktm', 'pulsar');
   
   print_r($pulsar->getMakeAndModel()); 
?>

工厂模式的主要困难是它会增加复杂性,对于优秀的程序员来说这是不可靠的.

策略模式

策略模式生成一个族算法并封装每个算法.这里的每个算法都应该在系列内互换.

<?php
   $elements = array(
      array(
         'id' => 2,
         'date' => '2011-01-01',
      ),
      array(
         'id' => 1,
         'date' => '2011-02-01'
      )
   );
   
   $collection = new ObjectCollection($elements);
   
   $collection->setComparator(new IdComparator());
   $collection->sort();
   
   echo "Sorted by ID:\n";
   print_r($collection->elements);
   
   $collection->setComparator(new DateComparator());
   $collection->sort();
   
   echo "Sorted by date:\n";
   print_r($collection->elements);
?>

模型视图控件

视图充当GUI,模型充当后端,控制充当适配器.这里三个部分相互连接.它将传递数据并相互访问数据.

模型视图控件