16 PHP Design Patterns introduced

Source: Internet
Author: User

This article mainly shares with you 16 PHP design pattern Introduction, the article involves some UML class diagram, in order to understand better, can read UML class diagram first. Hope to help everyone.

First, the factory model

The factory model can be divided into three types: Simple Factory mode, factory method mode, abstract Factory mode;
1. Simple Factory mode

Also known as the Static factory methods (static Factory method) mode, which belongs to the class-creation pattern. In the simple Factory mode, you can return instances of different classes depending on the parameters. The simple factory model specifically defines a class to be responsible for creating instances of other classes, and the instances that are created typically have a common parent class.

Role:

Factory class: Creating an instance of a specific product class: Abstract product class, defining a common interface for product subclasses Concreteproduct class: Specific product classes that implement interface functionality for product parent classes, or add custom features

UML Class Diagrams:

Example code:

<?php//Simple Factory mode 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 ()      } el Seif ($name = = ' dog ') {          return new Dog ();}}  } $cat = Factory::createanimal (' cat '); $dog = Factory::createanimal (' dog ');

The biggest advantage of the simple factory model is that the object creation and the use of the object separation, the creation of the object to the specialized factory class responsible, but its biggest disadvantage is that the factory class is not flexible enough to add new concrete products need to modify the factory class Judgment logic code, and when the product is more, the factory method code will be very complex.
2. Factory Method Mode

In this pattern, by defining an abstract core factory class and defining an interface for creating product objects, the work of creating a specific product instance is deferred to its factory subclass to complete. The advantage of this is that the core class only focuses on the interface definition of the factory class, and the specific product instance is given to the specific factory subclass to create. When the system needs to add a product is, do not need to modify the existing system code, only the addition of a specific product class and its corresponding factory sub-class, is the system extensibility has become very good, in line with the object-oriented programming of the open and closed principle;

Role:

Product: Abstract Products Class Concreteproduct: Specific product class factory: Abstract Factory class Concretefactory: Specific factory class

UML Class Diagrams:

Write a picture description here
Example 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 ();

The factory method model is a further abstraction and generalization of the simple factory model. Due to the use of object-oriented polymorphism, the factory method pattern preserves the advantages of a simple factory model and overcomes its drawbacks. In the factory method model, the core factory class is no longer responsible for the creation of all the products, but rather the specific creation work to the subclass to do. This core class is only responsible for giving the interface that a specific factory must implement, not the details of the product class being instantiated, which allows the factory method pattern to allow the system to introduce new products without modifying the factory role.
3. Abstract Factory mode

Provides an interface to create a series of related or interdependent objects without specifying their specific classes. Abstract Factory mode, also known as the kit mode, belongs to the object creation mode.

This pattern is a further extension of the factory method pattern. In the factory method model, a specific factory is responsible for producing a specific type of product, i.e. one-to-one relationships, but if a specific plant is needed to produce multiple product objects, then an abstract factory model is needed.

To facilitate understanding of this pattern, here are two concepts:

Product Hierarchy Structure: Product hierarchy structure is the product's inheritance structure, such as an abstract class is a television, its sub-category has Haier TV, Hisense TV, TCL TV, the abstract TV and the specific brand of television constitute a product hierarchy structure, abstract TV is the parent class, and the specific brand of the TV is its sub-category. Product family: In the abstract factory model, product family refers to the production of the same factory, located in different product grade structure of a group of products, such as Haier Electric factory production of Haier TV, Haier refrigerator, Haier TV is located in the TV product grade structure, Haier Refrigerator is located in the refrigerator product grade structure.

Role:

Abstract Factory (Abstractfactory): This role is at the core of the abstract factory model and is not related to the business logic of the application system. Specific Factory (Factory): This role creates an instance of the product directly under the client's call, which contains the logic to select the appropriate product object, which is closely related to the business logic of the application system. Abstract product (ABSTRACTPRODUCT): The class that holds this role is the parent class of objects created by the abstract factory pattern, or the interface specific products that they collectively own: any Product object created by the abstract factory pattern is an instance of a specific product class.

UML Class Diagrams:


Example code:

<?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 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 (); 

Ii. Builders ' model

AKA: Generator mode, which is an object building pattern. It can abstract the construction process of complex objects (abstract category) so that different implementations of this abstract process can construct objects of different manifestations (attributes).

The builder pattern is a step-by-step creation of a complex object that allows the user to build them only by specifying the type and content of the complex objects, and the user does not need to know the specifics of the build in-house. For example, a car is made up of wheels, engines, and other parts, and for the average person we use a complete car, and we need to join a constructor that will help us assemble the components into a complete car by order.

Role:

Builder: Abstract constructor class that specifies an abstract interface for each part that creates a product object. ConcreteBuilder: A concrete constructor class that implements the builder interface to construct and assemble individual parts of the product. Defines and clarifies the representation that it creates. Provides an interface for retrieving products director: Conductor, constructs an object that uses the builder interface. Product: Represents the complex object being constructed. Concreatebuilder creates an internal representation of the product and defines its assembly process. Contains the classes that define the components that comprise the assembly, including the interfaces that assemble the parts into the final product.

UML Class Diagrams:

Example code:

<?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 (' engine ');  } public Function Buildpartb () {$this-&GT;CAR-&GT;SETPARTB (' wheel ');  } public Function Buildpartc () {$this-&GT;CAR-&GT;SETPARTC (' other parts ');  } public Function GetResult () {return $this->car;  }}class car{protected $partA;  protected $partB;  protected $partC;  Public Function Setparta ($str) {$this->parta = $str;  The Public Function SETPARTB ($str) {$this-&GT;PARTB = $str;  The Public Function SETPARTC ($str) {$this-&GT;PARTC = $str;  Public function Show () {echo "This car by:". $this->parta. ', '. $this->partb. ', and '. $this-&GT;PARTC '; }}class director{ Public $myBuilder;      Public Function Startbuild () {$this->mybuilder->buildparta ();      $this-&GT;MYBUILDER-&GT;BUILDPARTB ();      $this-&GT;MYBUILDER-&GT;BUILDPARTC ();  return $this->mybuilder->getresult ();  The Public Function Setbuilder (Builder $builder) {$this->mybuilder = $builder; }} $carBuilder = new Carbuilder (); $director = new Director (); $director->setbuilder ($carBuilder); $newCar = $director- >startbuild (); $newCar->show ();

Three, single case mode

Singleton mode, also known as the list mode, is a common software design pattern. When you apply this pattern, the class of the Singleton object must guarantee that only one instance exists. Many times the entire system needs to have only one global object, which helps us coordinate the overall behavior of the system. The idea of implementing a singleton pattern is that a class can return an object with a reference (always the same) and a method that obtains the instance (which must be a static method, usually using the name getinstance); When we call this method, the reference is returned if the class holds a reference that is not empty. If the class holds a reference that is empty, create an instance of the class and give the instance a reference to the class, and we also define the class's constructor as a private method, so that the other code cannot instantiate the object of that class by calling its constructor. Only the static method provided by the class is used to obtain a unique instance of the class. ---wikipedia

The main points of the Singleton pattern are: A class can have only one instance; It must create its own instance itself; It must provide this instance to the entire system on its own. Singleton mode is an object-creation pattern.

Role:

Singleton: Single Case class

UML class Diagrams:

Example code:

<?php class singleton{  private static $instance;  Private constructor method, prohibit using new to create object  Private Function __construct () {} public  static function getinstance () {      if (!isset ( Self:: $instance)) {self          :: $instance = new self;      }      Return self:: $instance;  }  Make Clone method Private, Prohibit clone object  Private Function __clone () {} public  function say ()  {      echo "This is to create an object instance with Singleton mode < Br> ";  }  Public function operation ()  {      echo "Here you can add other methods and actions <br>";  }} $shiyanlou = new Singleton (); $shiyanlou = Singleton::getinstance (); $shiyanlou->say (); $shiyanlou->operation ( ); $newShiyanlou = Singleton::getinstance (); Var_dump ($shiyanlou = = = $newShiyanlou);

All of the above five modes belong to the creation mode, about the structure pattern,
See the Lab Building Tutorial "16 PHP Design Patterns in detail"

In this paper, some UML class diagrams are involved, in order to understand better, we can read UML class diagrams first.

First, the factory model

The factory model can be divided into three types: Simple Factory mode, factory method mode, abstract Factory mode;
1. Simple Factory mode

Also known as the Static factory methods (static Factory method) mode, which belongs to the class-creation pattern. In the simple Factory mode, you can return instances of different classes depending on the parameters. The simple factory model specifically defines a class to be responsible for creating instances of other classes, and the instances that are created typically have a common parent class.

Role:

Factory class: Creating an instance of a specific product class: Abstract product class, defining a common interface for product subclasses Concreteproduct class: Specific product classes that implement interface functionality for product parent classes, or add custom features

UML Class Diagrams:

Example code:

<?php//Simple Factory mode 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 ()      } el Seif ($name = = ' dog ') {          return new Dog ();}}  } $cat = Factory::createanimal (' cat '); $dog = Factory::createanimal (' dog ');

The biggest advantage of the simple factory model is that the object creation and the use of the object separation, the creation of the object to the specialized factory class responsible, but its biggest disadvantage is that the factory class is not flexible enough to add new concrete products need to modify the factory class Judgment logic code, and when the product is more, the factory method code will be very complex.
2. Factory Method Mode

In this pattern, by defining an abstract core factory class and defining an interface for creating product objects, the work of creating a specific product instance is deferred to its factory subclass to complete. The advantage of this is that the core class only focuses on the interface definition of the factory class, and the specific product instance is given to the specific factory subclass to create. When the system needs to add a product is, do not need to modify the existing system code, only the addition of a specific product class and its corresponding factory sub-class, is the system extensibility has become very good, in line with the object-oriented programming of the open and closed principle;

Role:

Product: Abstract Products Class Concreteproduct: Specific product class factory: Abstract Factory class Concretefactory: Specific factory class

UML Class Diagrams:

Write a picture description here
Example 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 (); 

The factory method model is a further abstraction and generalization of the simple factory model. Due to the use of object-oriented polymorphism, the factory method pattern preserves the advantages of a simple factory model and overcomes its drawbacks. In the factory method model, the core factory class is no longer responsible for the creation of all the products, but rather the specific creation work to the subclass to do. This core class is only responsible for giving the interface that a specific factory must implement, not the details of the product class being instantiated, which allows the factory method pattern to allow the system to introduce new products without modifying the factory role.
3. Abstract Factory mode

Provides an interface to create a series of related or interdependent objects without specifying their specific classes. Abstract Factory mode, also known as the kit mode, belongs to the object creation mode.

This pattern is a further extension of the factory method pattern. In the factory method model, a specific factory is responsible for producing a specific type of product, i.e. one-to-one relationships, but if a specific plant is needed to produce multiple product objects, then an abstract factory model is needed.

To facilitate understanding of this pattern, here are two concepts:

Product Hierarchy Structure: Product hierarchy structure is the product's inheritance structure, such as an abstract class is a television, its sub-category has Haier TV, Hisense TV, TCL TV, the abstract TV and the specific brand of television constitute a product hierarchy structure, abstract TV is the parent class, and the specific brand of the TV is its sub-category. Product family: In the abstract factory model, product family refers to the production of the same factory, located in different product grade structure of a group of products, such as Haier Electric factory production of Haier TV, Haier refrigerator, Haier TV is located in the TV product grade structure, Haier Refrigerator is located in the refrigerator product grade structure.

Role:

Abstract Factory (Abstractfactory): This role is at the core of the abstract factory model and is not related to the business logic of the application system. Specific Factory (Factory): This role creates an instance of the product directly under the client's call, which contains the logic to select the appropriate product object, which is closely related to the business logic of the application system. Abstract product (ABSTRACTPRODUCT): The class that holds this role is the parent class of objects created by the abstract factory pattern, or the interface specific products that they collectively own: any Product object created by the abstract factory pattern is an instance of a specific product class.

UML Class Diagrams:


Example code:

<?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 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 (); 

Ii. Builders ' model

AKA: Generator mode, which is an object building pattern. It can abstract the construction process of complex objects (abstract category) so that different implementations of this abstract process can construct objects of different manifestations (attributes).

The builder pattern is a step-by-step creation of a complex object that allows the user to build them only by specifying the type and content of the complex objects, and the user does not need to know the specifics of the build in-house. For example, a car is made up of wheels, engines, and other parts, and for the average person we use a complete car, and we need to join a constructor that will help us assemble the components into a complete car by order.

Role:

Builder: Abstract constructor class that specifies an abstract interface for each part that creates a product object. ConcreteBuilder: A concrete constructor class that implements the builder interface to construct and assemble individual parts of the product. Defines and clarifies the representation that it creates. Provides an interface for retrieving products director: Conductor, constructs an object that uses the builder interface. Product: Represents the complex object being constructed. Concreatebuilder creates an internal representation of the product and defines its assembly process. Contains the classes that define the components that comprise the assembly, including the interfaces that assemble the parts into the final product.

UML Class Diagrams:

Example code:

<?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 (' engine ');  } public Function Buildpartb () {$this-&GT;CAR-&GT;SETPARTB (' wheel ');  } public Function Buildpartc () {$this-&GT;CAR-&GT;SETPARTC (' other parts ');  } public Function GetResult () {return $this->car;  }}class car{protected $partA;  protected $partB;  protected $partC;  Public Function Setparta ($str) {$this->parta = $str;  The Public Function SETPARTB ($str) {$this-&GT;PARTB = $str;  The Public Function SETPARTC ($str) {$this-&GT;PARTC = $str;  Public function Show () {echo "This car by:". $this->parta. ', '. $this->partb. ', and '. $this-&GT;PARTC '; }}class director{ Public $myBuilder;      Public Function Startbuild () {$this->mybuilder->buildparta ();      $this-&GT;MYBUILDER-&GT;BUILDPARTB ();      $this-&GT;MYBUILDER-&GT;BUILDPARTC ();  return $this->mybuilder->getresult ();  The Public Function Setbuilder (Builder $builder) {$this->mybuilder = $builder; }} $carBuilder = new Carbuilder (); $director = new Director (); $director->setbuilder ($carBuilder); $newCar = $director- >startbuild (); $newCar->show ();

Three, single case mode

Singleton mode, also known as the list mode, is a common software design pattern. When you apply this pattern, the class of the Singleton object must guarantee that only one instance exists. Many times the entire system needs to have only one global object, which helps us coordinate the overall behavior of the system. The idea of implementing a singleton pattern is that a class can return an object with a reference (always the same) and a method that obtains the instance (which must be a static method, usually using the name getinstance); When we call this method, the reference is returned if the class holds a reference that is not empty. If the class holds a reference that is empty, create an instance of the class and give the instance a reference to the class, and we also define the class's constructor as a private method, so that the other code cannot instantiate the object of that class by calling its constructor. Only the static method provided by the class is used to obtain a unique instance of the class. ---wikipedia

The main points of the Singleton pattern are: A class can have only one instance; It must create its own instance itself; It must provide this instance to the entire system on its own. Singleton mode is an object-creation pattern.

Role:

Singleton: Single Case class

UML class Diagrams:

Example code:

<?php class singleton{  private static $instance;  Private constructor method, prohibit using new to create object  Private Function __construct () {} public  static function getinstance () {      if (!isset ( Self:: $instance)) {self          :: $instance = new self;      }      Return self:: $instance;  }  Make Clone method Private, Prohibit clone object  Private Function __clone () {} public  function say ()  {      echo "This is to create an object instance with Singleton mode < Br> ";  }  Public function operation ()  {      echo "Here you can add other methods and actions <br>";  }} $shiyanlou = new Singleton (); $shiyanlou = Singleton::getinstance (); $shiyanlou->say (); $shiyanlou->operation ( ); $newShiyanlou = Singleton::getinstance (); Var_dump ($shiyanlou = = = $newShiyanlou);

All of the above five modes are created mode, about the structural mode.
Related recommendations:

5 Kinds of JS design mode

About PHP design mode-Adapter approach

The prototype model of JS design mode is detailed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.