Heim  >  Artikel  >  Backend-Entwicklung  >  PHP 实战之设计模式:PHP 中的设计模式

PHP 实战之设计模式:PHP 中的设计模式

WBOY
WBOYOriginal
2016-07-23 08:54:42752Durchsuche

本文为翻译文章

原文地址:Design Patterns in PHP
如果打算学习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应用的开发中,常常用于允许在运行时为某个特定的类创建一个可访问的实例。

  1. /**
  2. * Singleton class
  3. */
  4. final class Product
  5. {
  6. /**
  7. * @var self
  8. */
  9. private static $instance;
  10. /**
  11. * @var mixed
  12. */
  13. public $mix;
  14. /**
  15. * Return self instance
  16. *
  17. * @return self
  18. */
  19. public static function getInstance() {
  20. if (!(self::$instance instanceof self)) {
  21. self::$instance = new self();
  22. }
  23. return self::$instance;
  24. }
  25. private function __construct() {
  26. }
  27. private function __clone() {
  28. }
  29. }
  30. $firstProduct = Product::getInstance();
  31. $secondProduct = Product::getInstance();
  32. $firstProduct->mix = 'test';
  33. $secondProduct->mix = 'example';
  34. print_r($firstProduct->mix);
  35. // example
  36. print_r($secondProduct->mix);
  37. // example
复制代码

在很多情况下,需要为系统中的多个类创建单例的构造方式,这样,可以建立一个通用的抽象父工厂方法:

  1. abstract class FactoryAbstract {
  2. protected static $instances = array();
  3. public static function getInstance() {
  4. $className = static::getClassName();
  5. if (!(self::$instances[$className] instanceof $className)) {
  6. self::$instances[$className] = new $className();
  7. }
  8. return self::$instances[$className];
  9. }
  10. public static function removeInstance() {
  11. $className = static::getClassName();
  12. if (array_key_exists($className, self::$instances)) {
  13. unset(self::$instances[$className]);
  14. }
  15. }
  16. final protected static function getClassName() {
  17. return get_called_class();
  18. }
  19. protected function __construct() { }
  20. final protected function __clone() { }
  21. }
  22. abstract class Factory extends FactoryAbstract {
  23. final public static function getInstance() {
  24. return parent::getInstance();
  25. }
  26. final public static function removeInstance() {
  27. parent::removeInstance();
  28. }
  29. }
  30. // using:
  31. class FirstProduct extends Factory {
  32. public $a = [];
  33. }
  34. class SecondProduct extends FirstProduct {
  35. }
  36. FirstProduct::getInstance()->a[] = 1;
  37. SecondProduct::getInstance()->a[] = 2;
  38. FirstProduct::getInstance()->a[] = 3;
  39. SecondProduct::getInstance()->a[] = 4;
  40. print_r(FirstProduct::getInstance()->a);
  41. // array(1, 3)
  42. print_r(SecondProduct::getInstance()->a);
  43. // array(2, 4)
复制代码
Registry

注册台模式并不是很常见,它也不是一个典型的创建模式,只是为了利用静态方法更方便的存取数据。

  1. /**
  2. * Registry class
  3. */
  4. class Package {
  5. protected static $data = array();
  6. public static function set($key, $value) {
  7. self::$data[$key] = $value;
  8. }
  9. public static function get($key) {
  10. return isset(self::$data[$key]) ? self::$data[$key] : null;
  11. }
  12. final public static function removeObject($key) {
  13. if (array_key_exists($key, self::$data)) {
  14. unset(self::$data[$key]);
  15. }
  16. }
  17. }
  18. Package::set('name', 'Package name');
  19. print_r(Package::get('name'));
  20. // Package name
复制代码
Factory(工厂模式)

工厂模式是另一种非常常用的模式,正如其名字所示:确实是对象实例的生产工厂。某些意义上,工厂模式提供了通用的方法有助于我们去获取对象,而不需要关心其具体的内在的实现。

  1. interface Factory {
  2. public function getProduct();
  3. }
  4. interface Product {
  5. public function getName();
  6. }
  7. class FirstFactory implements Factory {
  8. public function getProduct() {
  9. return new FirstProduct();
  10. }
  11. }
  12. class SecondFactory implements Factory {
  13. public function getProduct() {
  14. return new SecondProduct();
  15. }
  16. }
  17. class FirstProduct implements Product {
  18. public function getName() {
  19. return 'The first product';
  20. }
  21. }
  22. class SecondProduct implements Product {
  23. public function getName() {
  24. return 'Second product';
  25. }
  26. }
  27. $factory = new FirstFactory();
  28. $firstProduct = $factory->getProduct();
  29. $factory = new SecondFactory();
  30. $secondProduct = $factory->getProduct();
  31. print_r($firstProduct->getName());
  32. // The first product
  33. print_r($secondProduct->getName());
  34. // Second product
复制代码
AbstractFactory(抽象工厂模式)

有些情况下我们需要根据不同的选择逻辑提供不同的构造工厂,而对于多个工厂而言需要一个统一的抽象工厂:

  1. class Config {
  2. public static $factory = 1;
  3. }
  4. interface Product {
  5. public function getName();
  6. }
  7. abstract class AbstractFactory {
  8. public static function getFactory() {
  9. switch (Config::$factory) {
  10. case 1:
  11. return new FirstFactory();
  12. case 2:
  13. return new SecondFactory();
  14. }
  15. throw new Exception('Bad config');
  16. }
  17. abstract public function getProduct();
  18. }
  19. class FirstFactory extends AbstractFactory {
  20. public function getProduct() {
  21. return new FirstProduct();
  22. }
  23. }
  24. class FirstProduct implements Product {
  25. public function getName() {
  26. return 'The product from the first factory';
  27. }
  28. }
  29. class SecondFactory extends AbstractFactory {
  30. public function getProduct() {
  31. return new SecondProduct();
  32. }
  33. }
  34. class SecondProduct implements Product {
  35. public function getName() {
  36. return 'The product from second factory';
  37. }
  38. }
  39. $firstProduct = AbstractFactory::getFactory()->getProduct();
  40. Config::$factory = 2;
  41. $secondProduct = AbstractFactory::getFactory()->getProduct();
  42. print_r($firstProduct->getName());
  43. // The first product from the first factory
  44. print_r($secondProduct->getName());
  45. // Second product from second factory
复制代码
Object pool(对象池)

对象池可以用于构造并且存放一系列的对象并在需要时获取调用:

  1. class Product {
  2. protected $id;
  3. public function __construct($id) {
  4. $this->id = $id;
  5. }
  6. public function getId() {
  7. return $this->id;
  8. }
  9. }
  10. class Factory {
  11. protected static $products = array();
  12. public static function pushProduct(Product $product) {
  13. self::$products[$product->getId()] = $product;
  14. }
  15. public static function getProduct($id) {
  16. return isset(self::$products[$id]) ? self::$products[$id] : null;
  17. }
  18. public static function removeProduct($id) {
  19. if (array_key_exists($id, self::$products)) {
  20. unset(self::$products[$id]);
  21. }
  22. }
  23. }
  24. Factory::pushProduct(new Product('first'));
  25. Factory::pushProduct(new Product('second'));
  26. print_r(Factory::getProduct('first')->getId());
  27. // first
  28. print_r(Factory::getProduct('second')->getId());
  29. // second
复制代码
Lazy Initialization(延迟初始化)

对于某个变量的延迟初始化也是常常被用到的,对于一个类而言往往并不知道它的哪个功能会被用到,而部分功能往往是仅仅被需要使用一次。

  1. interface Product {
  2. public function getName();
  3. }
  4. class Factory {
  5. protected $firstProduct;
  6. protected $secondProduct;
  7. public function getFirstProduct() {
  8. if (!$this->firstProduct) {
  9. $this->firstProduct = new FirstProduct();
  10. }
  11. return $this->firstProduct;
  12. }
  13. public function getSecondProduct() {
  14. if (!$this->secondProduct) {
  15. $this->secondProduct = new SecondProduct();
  16. }
  17. return $this->secondProduct;
  18. }
  19. }
  20. class FirstProduct implements Product {
  21. public function getName() {
  22. return 'The first product';
  23. }
  24. }
  25. class SecondProduct implements Product {
  26. public function getName() {
  27. return 'Second product';
  28. }
  29. }
  30. $factory = new Factory();
  31. print_r($factory->getFirstProduct()->getName());
  32. // The first product
  33. print_r($factory->getSecondProduct()->getName());
  34. // Second product
  35. print_r($factory->getFirstProduct()->getName());
  36. // The first product
复制代码
Prototype(原型模式)

有些时候,部分对象需要被初始化多次。而特别是在如果初始化需要耗费大量时间与资源的时候进行预初始化并且存储下这些对象。

  1. interface Product {
  2. }
  3. class Factory {
  4. private $product;
  5. public function __construct(Product $product) {
  6. $this->product = $product;
  7. }
  8. public function getProduct() {
  9. return clone $this->product;
  10. }
  11. }
  12. class SomeProduct implements Product {
  13. public $name;
  14. }
  15. $prototypeFactory = new Factory(new SomeProduct());
  16. $firstProduct = $prototypeFactory->getProduct();
  17. $firstProduct->name = 'The first product';
  18. $secondProduct = $prototypeFactory->getProduct();
  19. $secondProduct->name = 'Second product';
  20. print_r($firstProduct->name);
  21. // The first product
  22. print_r($secondProduct->name);
  23. // Second product
复制代码
Builder(构造者)

构造者模式主要在于创建一些复杂的对象:

  1. class Product {
  2. private $name;
  3. public function setName($name) {
  4. $this->name = $name;
  5. }
  6. public function getName() {
  7. return $this->name;
  8. }
  9. }
  10. abstract class Builder {
  11. protected $product;
  12. final public function getProduct() {
  13. return $this->product;
  14. }
  15. public function buildProduct() {
  16. $this->product = new Product();
  17. }
  18. }
  19. class FirstBuilder extends Builder {
  20. public function buildProduct() {
  21. parent::buildProduct();
  22. $this->product->setName('The product of the first builder');
  23. }
  24. }
  25. class SecondBuilder extends Builder {
  26. public function buildProduct() {
  27. parent::buildProduct();
  28. $this->product->setName('The product of second builder');
  29. }
  30. }
  31. class Factory {
  32. private $builder;
  33. public function __construct(Builder $builder) {
  34. $this->builder = $builder;
  35. $this->builder->buildProduct();
  36. }
  37. public function getProduct() {
  38. return $this->builder->getProduct();
  39. }
  40. }
  41. $firstDirector = new Factory(new FirstBuilder());
  42. $secondDirector = new Factory(new SecondBuilder());
  43. print_r($firstDirector->getProduct()->getName());
  44. // The product of the first builder
  45. print_r($secondDirector->getProduct()->getName());
  46. // The product of second builder
复制代码
Structural Patterns Decorator(装饰器模式)

装饰器模式允许我们根据运行时不同的情景动态地为某个对象调用前后添加不同的行为动作。

  1. class HtmlTemplate {
  2. // any parent class methods
  3. }
  4. class Template1 extends HtmlTemplate {
  5. protected $_html;
  6. public function __construct() {
  7. $this->_html = "

    __text__

    ";
  8. }
  9. public function set($html) {
  10. $this->_html = $html;
  11. }
  12. public function render() {
  13. echo $this->_html;
  14. }
  15. }
  16. class Template2 extends HtmlTemplate {
  17. protected $_element;
  18. public function __construct($s) {
  19. $this->_element = $s;
  20. $this->set("

    " . $this->_html . "

    ");
  21. }
  22. public function __call($name, $args) {
  23. $this->_element->$name($args[0]);
  24. }
  25. }
  26. class Template3 extends HtmlTemplate {
  27. protected $_element;
  28. public function __construct($s) {
  29. $this->_element = $s;
  30. $this->set("" . $this->_html . "");
  31. }
  32. public function __call($name, $args) {
  33. $this->_element->$name($args[0]);
  34. }
  35. }
复制代码
Adapter(适配器模式)

这种模式允许使用不同的接口重构某个类,可以允许使用不同的调用方式进行调用:

  1. class SimpleBook {
  2. private $author;
  3. private $title;
  4. function __construct($author_in, $title_in) {
  5. $this->author = $author_in;
  6. $this->title = $title_in;
  7. }
  8. function getAuthor() {
  9. return $this->author;
  10. }
  11. function getTitle() {
  12. return $this->title;
  13. }
  14. }
  15. class BookAdapter {
  16. private $book;
  17. function __construct(SimpleBook $book_in) {
  18. $this->book = $book_in;
  19. }
  20. function getAuthorAndTitle() {
  21. return $this->book->getTitle().' by '.$this->book->getAuthor();
  22. }
  23. }
  24. // Usage
  25. $book = new SimpleBook("Gamma, Helm, Johnson, and Vlissides", "Design Patterns");
  26. $bookAdapter = new BookAdapter($book);
  27. echo 'Author and Title: '.$bookAdapter->getAuthorAndTitle();
  28. function echo $line_in) {
  29. echo $line_in."
    ";
  30. }
复制代码
Behavioral Patterns Strategy(策略模式)

测试模式主要为了让客户类能够更好地使用某些算法而不需要知道其具体的实现。

  1. interface OutputInterface {
  2. public function load();
  3. }
  4. class SerializedArrayOutput implements OutputInterface {
  5. public function load() {
  6. return serialize($arrayOfData);
  7. }
  8. }
  9. class JsonStringOutput implements OutputInterface {
  10. public function load() {
  11. return json_encode($arrayOfData);
  12. }
  13. }
  14. class ArrayOutput implements OutputInterface {
  15. public function load() {
  16. return $arrayOfData;
  17. }
  18. }
复制代码
Observer(观察者模式)

某个对象可以被设置为是可观察的,只要通过某种方式允许其他对象注册为观察者。每当被观察的对象改变时,会发送信息给观察者。

  1. interface Observer {
  2. function onChanged($sender, $args);
  3. }
  4. interface Observable {
  5. function addObserver($observer);
  6. }
  7. class CustomerList implements Observable {
  8. private $_observers = array();
  9. public function addCustomer($name) {
  10. foreach($this->_observers as $obs)
  11. $obs->onChanged($this, $name);
  12. }
  13. public function addObserver($observer) {
  14. $this->_observers []= $observer;
  15. }
  16. }
  17. class CustomerListLogger implements Observer {
  18. public function onChanged($sender, $args) {
  19. echo( "'$args' Customer has been added to the list \n" );
  20. }
  21. }
  22. $ul = new UserList();
  23. $ul->addObserver( new CustomerListLogger() );
  24. $ul->addCustomer( "Jack" );
复制代码
Chain of responsibility(责任链模式)

这种模式有另一种称呼:控制链模式。它主要由一系列对于某些命令的处理器构成,每个查询会在处理器构成的责任链中传递,在每个交汇点由处理器判断是否需要对它们进行响应与处理。每次的处理程序会在有处理器处理这些请求时暂停。

  1. interface Command {
  2. function onCommand($name, $args);
  3. }
  4. class CommandChain {
  5. private $_commands = array();
  6. public function addCommand($cmd) {
  7. $this->_commands[]= $cmd;
  8. }
  9. public function runCommand($name, $args) {
  10. foreach($this->_commands as $cmd) {
  11. if ($cmd->onCommand($name, $args))
  12. return;
  13. }
  14. }
  15. }
  16. class CustCommand implements Command {
  17. public function onCommand($name, $args) {
  18. if ($name != 'addCustomer')
  19. return false;
  20. echo("This is CustomerCommand handling 'addCustomer'\n");
  21. return true;
  22. }
  23. }
  24. class MailCommand implements Command {
  25. public function onCommand($name, $args) {
  26. if ($name != 'mail')
  27. return false;
  28. echo("This is MailCommand handling 'mail'\n");
  29. return true;
  30. }
  31. }
  32. $cc = new CommandChain();
  33. $cc->addCommand( new CustCommand());
  34. $cc->addCommand( new MailCommand());
  35. $cc->runCommand('addCustomer', null);
  36. $cc->runCommand('mail', null);
复制代码
PHP


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn