Summary of 16 design patterns in php-php Tutorial

Source: Internet
Author: User
Note: This tutorial is all taken from the lab building. [16 PHP design patterns]: describes the basic concepts and technical points of 16 common design patterns, the UML class diagram helps you understand the associations between classes in the design mode. for each design mode, PHP is used to complete a code example, so that you can easily follow the example to get started with the design mode. I. factory mode the factory mode can be divided into three types: simple factory mode, Factory method mode, and abstract Factory mode. 1. simple factory mode is also called StaticFactor

Note: This tutorial is all taken from the lab building. [16 PHP design patterns]: describes the basic concepts and technical points of 16 common design patterns, the UML class diagram helps you understand the associations between classes in the design mode. for each design mode, PHP is used to complete a code example, so that you can easily follow the example to get started with the design mode.

I. factory model

The factory mode can be divided into three types: simple factory mode, Factory method mode, and abstract Factory mode;

1. simple factory model

It is also called the Static Factory Method mode, which belongs to the class creation mode. In simple factory mode, instances of different classes can be returned based on different parameters. In simple factory mode, a class is defined specifically to create instances of other classes. the created instances usually share a common parent class.

Role:

  • Factory class: responsible for creating instances of specific products

  • Product class: abstract Product class, defining the public interfaces of Product subclass

  • ConcreteProduct class: the Product class that implements the interface function of the Product parent class. you can also add custom functions.

UML class diagram:

Sample code:

 ";}} Class Dog {function _ construct () {echo" I am Dog class
";}} 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 ');

The biggest advantage of the simple factory mode is the separation of object creation and object use, and the creation of objects is handed over to the dedicated factory class for responsibility. However, the biggest drawback is that the factory class is not flexible enough, to add a new product, you need to modify the judgment logic code of the factory class. In addition, the factory Method code will be very complicated when there are many products.

2. Factory method mode

In this mode, by defining an abstract core factory class and defining the interface for creating product objects, the work of creating a specific product instance is delayed until its factory subclass is completed. The advantage of this is that the core class only pays attention to the interface definition of the factory class, and the specific product instance is handed over to the specific factory subclass for creation. When a product needs to be added to a system, you do not need to modify the existing system code. Instead, you only need to add a specific product class and its corresponding factory subclass, which makes the system more scalable, compliant with the open and closed principles of object-oriented programming;

Role:

  • Product: abstract Product

  • ConcreteProduct: Product Type

  • Factory: Abstract Factory class

  • ConcreteFactory: Factory type

UML class diagram:

Sample code:

 ";  }  public function say(){      echo "I am Cat class 
"; }}class Dog implements Animal{ public function run(){ echo "I'm running fast
"; } public function say(){ echo "I am Dog class
"; }}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 mode is further abstract and promoted by the simple factory mode. Due to the use of object-oriented polymorphism, the factory method pattern maintains the advantages of the simple factory pattern and overcomes its shortcomings. In the factory method mode, the core factory class is no longer responsible for the creation of all products, but rather the specific creation work is handed over to the child class. This core class is only responsible for providing the interface that must be implemented by a specific factory, not for the details of product class instantiation, which allows the Factory method mode to allow the system to introduce new products without modifying the factory role.

3. Abstract factory model

Provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes. The abstract Factory mode, also known as the Kit mode, belongs to the object creation mode.

This mode is further extended to the factory method mode. In the factory method model, a specific factory is responsible for producing a specific type of products, that is, a one-to-one relationship. However, if a specific factory needs to produce multiple product objects, then we need to use the abstract factory model.

To facilitate understanding of this mode, two concepts are introduced here:

  • Product Level structure: Product level structure refers to the inheritance structure of products. for example, an abstract class is a TV set. its sub-classes include Haier TV sets, Hisense TV sets, and tcl TV sets, abstract TV sets and TV sets of a specific brand constitute a product level structure. abstract TV sets are the parent class, while TV sets of a specific brand are the child classes.

  • Product Family:In the abstract factory model, a product family refers to a group of products produced by the same factory in different product levels, such as Haier TV sets and Haier refrigerators produced by Haier Electric Appliance Factory, haier TV is located in the TV product level structure, and Haier refrigerator is located in the refrigerator product level structure.

Role:

  • AbstractFactory: This role is at the core of the Abstract factory model and has nothing to do with the business logic of the application system.

  • Factory: This role is used to create a product instance directly by calling the client. this role contains the logic for selecting the appropriate product object, this logic is closely related to the business logic of the application system.

  • AbstractProduct: the class that assumes this role is the parent class of the object created in the abstract Factory mode, or the interfaces they share.

  • Product: any Product object created in the abstract Factory mode is an instance of a specific Product category.

UML class diagram:

Sample code:

 ";  }  public function use()  {      echo "I'm watching TV 
"; }}interface PC{ public function work(); public function play();}class LenovoPc implements PC{ public function work() { echo "I'm working on a Lenovo computer
"; } public function play() { echo "Lenovo computers can be used to play games
"; }}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. Builder mode

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

The builder mode is used to create a complex object step by step. it allows users to build complex objects by specifying the types and content of complex objects. users do not need to know the specific internal building details. For example, a car consists of wheels, engines, and other parts. for ordinary people, we only use a complete car. at this time, we need to add a constructor, let him help us assemble these components into a complete car in order.

Role:

  • Builder: abstract constructor class, which specifies an abstract interface for each part of a Product object.

  • ConcreteBuilder: The constructor class that implements the Builder interface to construct and assemble various components of the product. Define and define the representation it creates. Provides an interface for retrieving products

  • Director: the conductor who constructs an object using the Builder interface.

  • Product: a complex object to be constructed. ConcreateBuilder creates an internal representation of the product and defines its assembly process.
    Class that includes defining components, including interfaces for assembling these components into a final product.

UML class diagram:

Sample code:

 Car = new Car ();} public function buildPartA () {$ this-> car-> setPartA ('engine');} public function buildPartB () {$ this-> car-> setPartB ('wheel');} public function buildPartC () {$ this-> car-> setPartC ('other parts ');} 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 car consists :". $ this-> partA. ','. $ this-> partB. ', and '. $ this-> partC. 'composite ';} class ctor {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 ();
III. Singleton mode

Singleton mode, Also calledList modeIs a common software design model. When this mode is applied, the class of the singleton object must ensure that only one instance exists. In many cases, the whole system only needs to have one global object, which is conducive to coordinating the overall behavior of the system.

The idea of implementing the Singleton mode is: a class can return a reference (always the same) to an object and a method to obtain the instance (must be a static method, the getInstance name is usually used). when we call this method, if the reference held by the class is not empty, this reference is returned, if the reference of the class persistence is null, create an instance of the class and assign the instance reference to the reference of the class persistence. at the same time, we also define the constructor of the class as a private method, in this way, the code in other places cannot instantiate the object of this class by calling the constructor of this class. only the static method provided by this class can be used to obtain the unique instance of this class.

--- Wikipedia

The main points of Singleton mode are: a class can only have one instance; it must create its own instance; it must provide this instance to the entire system. The Singleton mode is an object creation mode.

Role:

  • Singleton: Singleton class

UML class diagram:

Sample code:

 ";} Public function operation () {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 );

The above five modes belong to the creation mode. for the structure mode, click [16 PHP design modes] to view details ......

The above is a summary of the 16 design patterns in php. For more information, see other related articles in the first PHP community!

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.