Summary of 16 design patterns in PHP

零下一度
Release: 2023-03-10 17:50:01
Original
2003 people have browsed it

Note: This tutorial is all excerpted from the laboratory tutorial [Detailed Explanation of 16 PHP Design Patterns]: It mainly introduces the basic concepts and technical points of 16 commonly used design patterns, and uses UML class diagrams to help understand the design patterns. The relationship between each class, and a code example using PHP for each design pattern, allowing you to easily get started with the design pattern by following the example.

1. Factory pattern

Factory pattern can be divided into three types of patterns: simple factory pattern, factory method pattern, abstract factory pattern;

1.Simple Factory pattern

is also called the static factory method (Static Factory Method) pattern, which belongs to the class creation pattern. In the simple factory pattern, instances of different classes can be returned according to different parameters. The simple factory pattern specifically defines a class to be responsible for creating instances of other classes. The created instances usually have a common parent class.

Role:

  • Factory class: Responsible for creating instances of specific products

  • Product class: Abstract product class, defines the public interface of product subclasses

  • ConcreteProduct class: concrete product class, implements the interface function of the Product parent class, and can also add custom functions

UML class diagram:

Summary of 16 design patterns in PHP

Sample code:

<?php  
//简单工厂模式
class Cat
{
  function __construct()
  {
      echo "I am Cat class <br>";
  }
}
class Dog
{
  function __construct()
  {
      echo "I am Dog class <br>";
  }
}
class Factory
{
  public static function CreateAnimal($name){
      if ($name == 'cat') {
          return new Cat();
      } elseif ($name == 'dog') {
          return new Dog();
      }
  }
}

$cat = Factory::CreateAnimal('cat');
$dog = Factory::CreateAnimal('dog');
Copy after login

Simple factory The biggest advantage of the pattern is to separate the creation of objects and the use of objects, and leave the creation of objects to a specialized factory class. However, its biggest disadvantage is that the factory class is not flexible enough. Adding new specific products requires modifying the judgment logic of the factory class. Code, and when there are many products, the factory method code will be very complex.

2. Factory method pattern

In this pattern, by defining an abstract core factory class and defining an interface for creating product objects, the work of creating specific product instances is delayed to its factory subclasses Go and finish. The advantage of this is that the core class only focuses on the interface definition of the factory class, and specific product instances are left to the specific factory subclass to create. When the system needs to add a new product, there is no need to modify the existing system code. You only need to add a specific product class and its corresponding factory subclass. This makes the system more scalable and conforms to the opening and closing principle of object-oriented programming;

Role:

  • Product: Abstract product class

  • ConcreteProduct: Concrete product class

  • Factory: Abstract Factory Class

  • ConcreteFactory: Concrete Factory Class

UML Class Diagram :

Summary of 16 design patterns in PHP

Sample code:

<?php  
interface Animal{
  public function run();
  public function say();
}
class Cat implements Animal
{
  public function run(){
      echo "I ran slowly <br>";
  }
  public function say(){
      echo "I am Cat class <br>";
  }
}
class Dog implements Animal
{
  public function run(){
      echo "I'm running fast <br>";
  }
  public function say(){
      echo "I am Dog class <br>";
  }
}
abstract class Factory{
  abstract static function createAnimal();
}
class CatFactory extends Factory
{
  public static function createAnimal()
  {
      return new Cat();
  }
}
class DogFactory extends Factory
{
  public static function createAnimal()
  {
      return new Dog();
  }
}

$cat = CatFactory::createAnimal();
$cat->say();
$cat->run();

$dog = DogFactory::createAnimal();
$dog->say();
$dog->run();
Copy after login

The factory method pattern is a further abstraction and promotion of the simple factory pattern. Due to the use of object-oriented polymorphism, the factory method pattern maintains the advantages of the simple factory pattern and overcomes its disadvantages. In the factory method pattern, the core factory class is no longer responsible for the creation of all products, but leaves the specific creation work to subclasses. This core class is only responsible for giving the interface that a specific factory must implement, and is not responsible for the details of how the product class is instantiated. This allows the factory method pattern to allow the system to introduce new products without modifying the factory role.

3. Abstract Factory Pattern

Provides an interface for creating a series of related or interdependent objects without specifying their specific classes. Abstract Factory Pattern, also known as Kit Pattern, is an object creation pattern.

This pattern is a further extension of the factory method pattern. In the factory method pattern, a specific factory is responsible for producing a specific type of product, that is, a one-to-one relationship. However, if a specific factory is required to produce multiple product objects, then the abstract factory pattern needs to be used.

In order to facilitate the understanding of this model, two concepts are introduced here:

  • Product level structure: The product level structure is the inheritance structure of the product, such as An abstract class is a TV, and its subclasses include Haier TV, Hisense TV, and TCL TV. A product hierarchy is formed between the abstract TV and the specific brand of TV. The abstract TV is the parent class, and the abstract TV is the parent class. Specific brands of televisions are its subcategories.

  • Product family: In the abstract factory pattern, a product family refers to a group of products produced by the same factory and located in different product hierarchy structures, such as Haier TVs and Haier refrigerators are produced by Haier Electrical Appliance Factory. Haier TVs are located in the TV product level structure, and Haier refrigerators are located in the refrigerator product level structure.

Role:

  • Abstract Factory (AbstractFactory): This role is the core of the Abstract Factory pattern and is Has nothing to do with the business logic of the application system.

  • 具体工厂(Factory):这个角色直接在客户端的调用下创建产品的实例,这个角色含有选择合适的产品对象的逻辑,而这个逻辑是与应用系统商业逻辑紧密相关的。

  • 抽象产品(AbstractProduct):担任这个角色的类是抽象工厂模式所创建的对象的父类,或它们共同拥有的接口

  • 具体产品(Product):抽象工厂模式所创建的任何产品对象都是一个具体的产品类的实例。

UML类图:

Summary of 16 design patterns in PHP

示例代码:

<?php  

interface TV{
  public function open();
  public function use();
}

class HaierTv implements TV
{
  public function open()
  {
      echo "Open Haier TV <br>";
  }

  public function use()
  {
      echo "I'm watching TV <br>";
  }
}

interface PC{
  public function work();
  public function play();
}

class LenovoPc implements PC
{
  public function work()
  {
      echo "I'm working on a Lenovo computer <br>";
  }
  public function play()
  {
      echo "Lenovo computers can be used to play games <br>";
  }
}

abstract class Factory{
  abstract public static function createPc();
  abstract public static function createTv();
}

class ProductFactory extends Factory
{
  public static function createTV()
  {
      return new HaierTv();
  }
  public static function createPc()
  {
      return new LenovoPc();
  }
}

$newTv = ProductFactory::createTV();
$newTv->open();
$newTv->use();

$newPc = ProductFactory::createPc();
$newPc->work();
$newPc->play();
Copy after login

二、建造者模式

又名:生成器模式,是一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。

建造者模式是一步一步创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。例如,一辆汽车由轮子,发动机以及其他零件组成,对于普通人而言,我们使用的只是一辆完整的车,这时,我们需要加入一个构造者,让他帮我们把这些组件按序组装成为一辆完整的车。

角色:

  • Builder:抽象构造者类,为创建一个Product对象的各个部件指定抽象接口。

  • ConcreteBuilder:具体构造者类,实现Builder的接口以构造和装配该产品的各个部件。定义并明确它所创建的表示。提供一个检索产品的接口

  • Director:指挥者,构造一个使用Builder接口的对象。

  • Product:表示被构造的复杂对象。ConcreateBuilder创建该产品的内部表示并定义它的装配过程。
    包含定义组成部件的类,包括将这些部件装配成最终产品的接口。

UML类图:

Summary of 16 design patterns in PHP

示例代码:

<?php  
/**
* chouxiang builer
*/
abstract class Builder
{
  protected $car;
  abstract public function buildPartA();
  abstract public function buildPartB();
  abstract public function buildPartC();
  abstract public function getResult();
}

class CarBuilder extends Builder
{
  function __construct()
  {
      $this->car = new Car();
  }
  public function buildPartA(){
      $this->car->setPartA('发动机');
  }

  public function buildPartB(){
      $this->car->setPartB('轮子');
  }

  public function buildPartC(){
      $this->car->setPartC('其他零件');
  }

  public function getResult(){
      return $this->car;
  }
}

class Car
{
  protected $partA;
  protected $partB;
  protected $partC;

  public function setPartA($str){
      $this->partA = $str;
  }

  public function setPartB($str){
      $this->partB = $str;
  }

  public function setPartC($str){
      $this->partC = $str;
  }

  public function show()
  {
      echo "这辆车由:".$this->partA.','.$this->partB.',和'.$this->partC.'组成';
  }
}

class Director
{
  public $myBuilder;

  public function startBuild()
  {
      $this->myBuilder->buildPartA();
      $this->myBuilder->buildPartB();
      $this->myBuilder->buildPartC();
      return $this->myBuilder->getResult();
  }

  public function setBuilder(Builder $builder)
  {
      $this->myBuilder = $builder;
  }
}

$carBuilder = new CarBuilder();
$director = new Director();
$director->setBuilder($carBuilder);
$newCar = $director->startBuild();
$newCar->show();
Copy after login

三、单例模式

单例模式,也叫单子模式,是一种常用的软件设计模式。在应用这个模式时,单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。

实现单例模式的思路是:一个类能返回对象一个引用(永远是同一个)和一个获得该实例的方法(必须是静态方法,通常使用getInstance这个名称);当我们调用这个方法时,如果类持有的引用不为空就返回这个引用,如果类保持的引用为空就创建该类的实例并将实例的引用赋予该类保持的引用;同时我们还将该类的构造函数定义为私有方法,这样其他处的代码就无法通过调用该类的构造函数来实例化该类的对象,只有通过该类提供的静态方法来得到该类的唯一实例。

---维基百科

单例模式的要点有:某个类只能有一个实例;它必须自行创建本身的实例;它必须自行向整个系统提供这个实例。单例模式是一种对象创建型模式。

角色:

  • Singleton:单例类

UML 类图:

Summary of 16 design patterns in PHP

示例代码:

<?php  

class Singleton
{
  private static $instance;
  //私有构造方法,禁止使用new创建对象
  private function __construct(){}

  public static function getInstance(){
      if (!isset(self::$instance)) {
          self::$instance = new self;
      }
      return self::$instance;
  }
  //将克隆方法设为私有,禁止克隆对象
  private function __clone(){}

  public function say()
  {
      echo "这是用单例模式创建对象实例 <br>";
  }
  public function operation()
  {
      echo "这里可以添加其他方法和操作 <br>";
  }
}

// $shiyanlou = new Singleton();
$shiyanlou = Singleton::getInstance();
$shiyanlou->say();
$shiyanlou->operation();

$newShiyanlou = Singleton::getInstance();
var_dump($shiyanlou === $newShiyanlou);
Copy after login

上述的五个模式均属于创建型模式,关于结构型模式,点击【16个PHP设计模式详解】即可查看了……

The above is the detailed content of Summary of 16 design patterns in PHP. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template