Description: this course – [16 PHP design patterns, rounding 】 : this paper mainly introduces the basic concept of the 16 common design patterns and technology main points, through UML class diagram to help understanding of the relationship between the classes in design mode, for each design pattern using PHP completed a code sample, let you follow examples easy introduction to design patterns.

The factory pattern

Factory model can be divided into three types: simple factory model, factory method model and abstract factory model.

1. Simple factory mode

Also known as the Static Factory Method pattern, it belongs to the class creation pattern. In the simple factory pattern, you can return instances of different classes depending on the parameters. The simple factory pattern specifically defines a class that is responsible for creating instances of other classes, which usually have a common parent class.

Role:

  • Factory class: Responsible for creating instances of specific products
  • Product class: Abstract Product class that defines a common interface for Product subclasses
  • ConcreteProduct class: ConcreteProduct class that implements interface functions of the Product parent class, or can add custom functions

UML class diagram:





Enter a description of the picture here

Sample code:


         
// Simple factory mode
class Cat
{
  function __construct(a)
  {
      echo "I am Cat class <br>"; }}class Dog
{
  function __construct(a)
  {
      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 the code

The greatest advantage of simple factory pattern is to realize the use of object creation and separation, the object creation to the specialized factory class is responsible for, but the biggest drawback is that the factory class is not flexible, adding new specific products need to modify the factory class judgment logic code, and are too many products, the factory method code will be very complicated.

2. Factory method pattern

In this pattern, by defining an abstract core factory class and defining the interface for creating product objects, the creation of concrete product instances is deferred to its factory subclasses. The advantage of this is that the core class only focuses on the interface definition of the factory class, leaving the concrete product instances to be created by the concrete factory subclasses. When the system needs to add a new product is, there is no need to modify the existing system code, only need to add a specific product class and its corresponding factory subclass, is the system expansibility becomes very good, in line with the open and close principle of object-oriented programming;

Role:

  • Product: Abstract Product class
  • ConcreteProduct: ConcreteProduct class
  • Factory: Abstract Factory class
  • ConcreteFactory: ConcreteFactory class

UML class diagram:





Enter a description of the picture here

Sample code:


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

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

$dog = DogFactory::createAnimal();
$dog->say();
$dog->run();Copy the code

The factory method pattern is a further abstraction and extension of the simple factory pattern. The factory method pattern retains the advantages of the simple factory pattern and overcomes its disadvantages by using object-oriented polymorphism. In the factory method pattern, the core factory class is no longer responsible for the creation of all products, but hands off the specific creation to subclasses. This core class is only responsible for giving the interfaces that a particular factory must implement, not the details of how the product class is instantiated, allowing the factory method pattern to allow the system to introduce new products without changing the factory role.

3. Abstract factory pattern

Provides an interface for creating a series of related or interdependent objects without specifying their concrete classes. The Abstract factory pattern, also known as the Kit pattern, belongs to the 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 class of products, that is, a one-to-one relationship. However, if you need a specific factory to produce multiple product objects, then you need to use the abstract factory pattern.

To understand this pattern, two concepts are introduced:

  • Product hierarchy: hierarchy the inheritance structure of products, such as an abstract class is a TV set, its subclasses are haier, hisense TV, TCL, TVS, abstract and specific brands, constitute a product hierarchy between abstraction is the parent of the television, and specific brand of TV set is its subclasses.
  • Product family: in the abstract factory pattern, product family is to point to by the same factory, located in different level of product structure in a set of products, such as haier electrical appliances factory production of TV sets, refrigerators, haier haier haier TV in the TV product hierarchy, haier refrigerators in the refrigerator in the hierarchy.

Role:

  • AbstractFactory: in this role is the core of the AbstractFactory pattern, independent of the business logic of the application system.
  • Factory: This role creates instances of products directly on client calls. This role contains the logic to select the appropriate product object, which is closely related to the application business logic.
  • AbstractProduct: A class in this role is a parent class of the objects created by the abstract factory pattern, or an interface that they share
  • Concrete Product: Any Product object created by the Abstract factory pattern is an instance of a concrete Product class.

UML class diagram:





Enter a description of the picture here

Sample code:


         

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

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

  public function use(a)
  {
      echo "I'm watching TV <br>"; }}interface PC{
  public function work(a);
  public function play(a);
}

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

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

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

$newPc = ProductFactory::createPc();
$newPc->work();
$newPc->play();Copy the code

Builder model

Also known as generator pattern, is an object construction pattern. It can abstract the construction process of complex objects (abstract classes), so that different implementation methods of this abstract process can construct objects with different manifestations (attributes).

The Builder pattern, which creates a complex object step by step, allows users to build complex objects simply by specifying their type and content, without needing to know the specific build details inside. For example, a car is made up of wheels, engine and other parts. For ordinary people, we only use a complete car. At this time, we need to join a builder and let him help us assemble these components into a complete car.

Role:

  • Builder: Abstract constructor class that specifies the abstract interface for the parts that create a Product object.
  • ConcreteBuilder: Concrete constructor class that implements the interface to the Builder to construct and assemble parts of the product. Define and specify the representation it creates. Provide an interface to retrieve products
  • Director: the Director that constructs an object using the Builder interface.
  • Product: represents a complex object being constructed. ConcreateBuilder creates an internal representation of the product and defines its assembly process. Contains classes that define the components, including interfaces that assemble them into the final product.

UML class diagram:





Enter a description of the picture here

Sample code:


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

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

  public function buildPartB(a){
      $this->car->setPartB('the wheel');
  }

  public function buildPartC(a){
      $this->car->setPartC('Other Parts');
  }

  public function getResult(a){
      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(a)
  {
      echo "This car is made of:".$this->partA.', '.$this->partB.', and '.$this->partC.'composition'; }}class Director
{
  public $myBuilder;

  public function startBuild(a)
  {
      $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 the code

The singleton pattern

Singleton pattern, also called monad pattern, is a common software design pattern. When this pattern is applied, the singleton class must ensure that only one instance exists. Many times the whole system only needs to have one global object, which helps us coordinate the behavior of the whole system.

The idea behind the singleton pattern is that a class can return a reference to an object (always the same) and a method to get that instance (it must be static, usually using the name getInstance). When we call this method, we return the reference held by the class if it is not empty, and create an instance of the class if the reference held by the class is empty and assign the instance’s reference to the reference held by the class. We also define the constructor of the class as a private method, so that code elsewhere cannot call the constructor to instantiate objects of the class, only to get a unique instance of the class through static methods provided by the class.

— Wikipedia

The essentials of the singleton pattern are: there can be only one instance of a class; It must create its own instance; It must provide this instance to the entire system itself. The singleton pattern is an object creation pattern.

Role:

  • Singleton: Singleton class

UML class diagram:





Enter a description of the picture here

Sample code:


         

class Singleton
{
  private static $instance;
  // Private constructor that disallows object creation with new
  private function __construct(a){}

  public static function getInstance(a){
      if (!isset(self::$instance)) {
          self::$instance = new self;
      }
      return self::$instance;
  }
  // Make the cloning method private and forbid object cloning
  private function __clone(a){}

  public function say(a)
  {
      echo "This is using the singleton pattern to create object instances 

"
; } public function operation(a) { echo "Other methods and operations can be added here."; }}// $shiyanlou = new Singleton(); $shiyanlou = Singleton::getInstance(); $shiyanlou->say(); $shiyanlou->operation(); $newShiyanlou = Singleton::getInstance(); var_dump($shiyanlou === $newShiyanlou);
Copy the code

The above five patterns are all creation patterns. For structural patterns, click on 16 PHP design patterns to see…