> 原文地址:
design patterns in php
本文主要讨论下web开发中,准确而言,是php开发中的相关的设计模式及其应用。有经验的开发者肯定对于设计模式非常熟悉,但是本文主要是针对那些初级的开发者。首先我们要搞清楚到底什么是设计模式,设计模式并不是一种用来解释的模式,它们并不是像链表那样的常见的数据结构,也不是某种特殊的应用或者框架设计。事实上,设计模式的解释如下:
descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context.
另一方面,设计模式提供了一种广泛的可重用的方式来解决我们日常编程中常常遇见的问题。设计模式并不一定就是一个类库或者第三方框架,它们更多的表现为一种思想并且广泛地应用在系统中。它们也表现为一种模式或者模板,可以在多个不同的场景下用于解决问题。设计模式可以用于加速开发,并且将很多大的想法或者设计以一种简单地方式实现。当然,虽然设计模式在开发中很有作用,但是千万要避免在不适当的场景误用它们。
目前常见的设计模式主要有23种,根据使用目标的不同可以分为以下三大类:
创建模式:用于创建对象从而将某个对象从实现中解耦合。
架构模式:用于在不同的对象之间构造大的对象结构。
行为模式:用于在不同的对象之间管理算法、关系以及职责。
creational patterns singleton(单例模式) 单例模式是最常见的模式之一,在web应用的开发中,常常用于允许在运行时为某个特定的类创建一个可访问的实例。
mix = 'test';$secondproduct->mix = 'example';print_r($firstproduct->mix);// exampleprint_r($secondproduct->mix);// example
在很多情况下,需要为系统中的多个类创建单例的构造方式,这样,可以建立一个通用的抽象父工厂方法:
a[] = 1;secondproduct::getinstance()->a[] = 2;firstproduct::getinstance()->a[] = 3;secondproduct::getinstance()->a[] = 4;print_r(firstproduct::getinstance()->a);// array(1, 3)print_r(secondproduct::getinstance()->a);// array(2, 4)
registry 注册台模式并不是很常见,它也不是一个典型的创建模式,只是为了利用静态方法更方便的存取数据。
getproduct();print_r($firstproduct->getname());// the first productprint_r($secondproduct->getname());// second product
abstractfactory(抽象工厂模式) 有些情况下我们需要根据不同的选择逻辑提供不同的构造工厂,而对于多个工厂而言需要一个统一的抽象工厂:
getproduct();config::$factory = 2;$secondproduct = abstractfactory::getfactory()->getproduct();print_r($firstproduct->getname());// the first product from the first factoryprint_r($secondproduct->getname());// second product from second factory
object pool(对象池) 对象池可以用于构造并且存放一系列的对象并在需要时获取调用:
id = $id; } public function getid() { return $this->id; }}class factory { protected static $products = array(); public static function pushproduct(product $product) { self::$products[$product->getid()] = $product; } public static function getproduct($id) { return isset(self::$products[$id]) ? self::$products[$id] : null; } public static function removeproduct($id) { if (array_key_exists($id, self::$products)) { unset(self::$products[$id]); } }}factory::pushproduct(new product('first'));factory::pushproduct(new product('second'));print_r(factory::getproduct('first')->getid());// firstprint_r(factory::getproduct('second')->getid());// second
lazy initialization(延迟初始化) 对于某个变量的延迟初始化也是常常被用到的,对于一个类而言往往并不知道它的哪个功能会被用到,而部分功能往往是仅仅被需要使用一次。
firstproduct) { $this->firstproduct = new firstproduct(); } return $this->firstproduct; } public function getsecondproduct() { if (!$this->secondproduct) { $this->secondproduct = new secondproduct(); } return $this->secondproduct; }}class firstproduct implements product { public function getname() { return 'the first product'; }}class secondproduct implements product { public function getname() { return 'second product'; }}$factory = new factory();print_r($factory->getfirstproduct()->getname());// the first productprint_r($factory->getsecondproduct()->getname());// second productprint_r($factory->getfirstproduct()->getname());// the first product
prototype(原型模式) 有些时候,部分对象需要被初始化多次。而特别是在如果初始化需要耗费大量时间与资源的时候进行预初始化并且存储下这些对象。
product = $product; } public function getproduct() { return clone $this->product; }}class someproduct implements product { public $name;}$prototypefactory = new factory(new someproduct());$firstproduct = $prototypefactory->getproduct();$firstproduct->name = 'the first product';$secondproduct = $prototypefactory->getproduct();$secondproduct->name = 'second product';print_r($firstproduct->name);// the first productprint_r($secondproduct->name);// second product
builder(构造者) 构造者模式主要在于创建一些复杂的对象:
name = $name; } public function getname() { return $this->name; }}abstract class builder { protected $product; final public function getproduct() { return $this->product; } public function buildproduct() { $this->product = new product(); }}class firstbuilder extends builder { public function buildproduct() { parent::buildproduct(); $this->product->setname('the product of the first builder'); }}class secondbuilder extends builder { public function buildproduct() { parent::buildproduct(); $this->product->setname('the product of second builder'); }}class factory { private $builder; public function __construct(builder $builder) { $this->builder = $builder; $this->builder->buildproduct(); } public function getproduct() { return $this->builder->getproduct(); }}$firstdirector = new factory(new firstbuilder());$seconddirector = new factory(new secondbuilder());print_r($firstdirector->getproduct()->getname());// the product of the first builderprint_r($seconddirector->getproduct()->getname());// the product of second builder
structural patterns decorator(装饰器模式) 装饰器模式允许我们根据运行时不同的情景动态地为某个对象调用前后添加不同的行为动作。
_html = __text__
; } public function set($html) { $this->_html = $html; } public function render() { echo $this->_html; }} class template2 extends htmltemplate { protected $_element; public function __construct($s) { $this->_element = $s; $this->set( . $this->_html . ); } public function __call($name, $args) { $this->_element->$name($args[0]); }} class template3 extends htmltemplate { protected $_element; public function __construct($s) { $this->_element = $s; $this->set( . $this->_html . ); } public function __call($name, $args) { $this->_element->$name($args[0]); }}
adapter(适配器模式) 这种模式允许使用不同的接口重构某个类,可以允许使用不同的调用方式进行调用:
author = $author_in; $this->title = $title_in; } function getauthor() { return $this->author; } function gettitle() { return $this->title; }}class bookadapter { private $book; function __construct(simplebook $book_in) { $this->book = $book_in; } function getauthorandtitle() { return $this->book->gettitle().' by '.$this->book->getauthor(); }}// usage$book = new simplebook(gamma, helm, johnson, and vlissides, design patterns);$bookadapter = new bookadapter($book);echo 'author and title: '.$bookadapter->getauthorandtitle();function echo $line_in) { echo $line_in.
;}
behavioral patterns strategy(策略模式) 测试模式主要为了让客户类能够更好地使用某些算法而不需要知道其具体的实现。
onchanged($this, $name); } public function addobserver($observer) { $this->_observers []= $observer; }}class customerlistlogger implements observer { public function onchanged($sender, $args) { echo( '$args' customer has been added to the list \n ); }}$ul = new userlist();$ul->addobserver( new customerlistlogger() );$ul->addcustomer( jack );
chain of responsibility(责任链模式) 这种模式有另一种称呼:控制链模式。它主要由一系列对于某些命令的处理器构成,每个查询会在处理器构成的责任链中传递,在每个交汇点由处理器判断是否需要对它们进行响应与处理。每次的处理程序会在有处理器处理这些请求时暂停。
_commands[]= $cmd; } public function runcommand($name, $args) { foreach($this->_commands as $cmd) { if ($cmd->oncommand($name, $args)) return; } }}class custcommand implements command { public function oncommand($name, $args) { if ($name != 'addcustomer') return false; echo(this is customercommand handling 'addcustomer'\n); return true; }}class mailcommand implements command { public function oncommand($name, $args) { if ($name != 'mail') return false; echo(this is mailcommand handling 'mail'\n); return true; }}$cc = new commandchain();$cc->addcommand( new custcommand());$cc->addcommand( new mailcommand());$cc->runcommand('addcustomer', null);$cc->runcommand('mail', null);