PHP设计模式
微软的设计模式理论是:“该文档引入了模式,然后将它们呈现在一个存储库或目录中,这是为了帮助您找到解决问题的正确…
微软的设计模式理论是:“该文档引入了模式,然后将它们呈现在一个存储库或目录中,这是为了帮助您找到解决问题的正确模式组合而组织的。”
设计模式的例子
单例
一个类有一个实例,它提供了一个全局访问点,下面的代码将解释有关单例的概念。
<?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()
工厂
A类简单创建对象并且您想要使用该对象,下面的示例将解释有关工厂设计模式。
<?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,模型行为作为后端,控制充当适配器。这里有三个部分互相连接。它将传递数据并访问彼此之间的数据。
还没有任何评论,赶紧来占个楼吧!