Summarize 16 Design Patterns in PHP

Source: Internet
Author: User
Tags php class

Description: This tutorial all cut off from the experimental building tutorial "16 PHP Design Patterns in detail": The main introduction of 16 common design patterns of basic concepts and technical points, through the UML class diagram to help understand the design patterns in the relationship between the various classes, for each design pattern using PHP to complete a code example, Lets you follow the example easy to get started design mode.

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: an instance responsible for creating a specific product

    • Product Class: Abstract products class, defining public interfaces for product subclasses

    • Concreteproduct Class: Specific product class, implement the interface function of product parent class, also can add custom function

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 Categories

    • Factory: Abstract Factory class

    • Concretefactory: Specific Factory class

UML Class Diagrams:

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, then 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 television is its sub-category.

    • Product Family: in the abstract factory model, product family refers to a group of products produced by the same factory, located in different product grade structure, such as Haier TV Haier electric factory production, Haier Refrigerator, Haier TV set in the TV product hierarchy, 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 interfaces they share

    • Specific product: The abstract Factory mode any product object created 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: The 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);

The above five models belong to the creation mode, about the structure mode, click on the "16 PHP design mode" To view ...

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.