Menu Close

PHP – 设计模式

Microsoft设计模式理论是“文档引入模式,然后将它们呈现在一个存储库或目录中,该库是为了帮助您找到解决问题的正确组合模式。

设计模式的例子

单身人士

一个类有一个实例,它提供了一个全局接入点,以下代码将解释单例概念。

 

<?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()

工厂设计模式

简单类创建对象,并且要使用该对象,以下示例将说明工厂设计模式。

 

<?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,模型作为后端,控制作为适配器。这三个部分互相连接。它将传递数据并相互访问数据。

 

Model View Control

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in PHP教程

Related Posts