PHP design pattern (1) factory mode

Time:2020-11-22

This paper describes the PHP design pattern (1) factory mode. For your reference, the details are as follows:

In object-oriented programming, the most common method is to generate an object instance by a new operator. The new operator is used to construct the object instance. However, in some cases, the new operator directly generates objects, which will bring some problems. For example, the creation of many types of objects requires a series of steps: you may need to calculate or obtain the initial settings of the object; you may choose which sub object instance to generate; or you must first create some auxiliary objects before generating the objects you need. In these cases, the creation of new objects is a “process”, not just an operation, like a gear drive in a large machine.

Pattern problem: how can you easily and easily construct object instances without paying attention to the details and complex process of constructing object instances?

Solution: set up a factory to create objects.

realization:

1、 Introduction

1) there is no factory era: if there is no industrial revolution, if a customer wants a BMW, the general practice is to create a BMW and use it.
2) simple factory model: Industrial Revolution appeared later. Users don’t have to create a BMW. Because the customer has a factory to help him create BMW. This factory can build any car he wants. Like the 320i train. On the creation of this series of cars. That is, factories can create products.
3) factory approach model era: in order to satisfy customers, more and more BMW series are available, such as 320i, 523i, 30li and so on. One factory cannot create all BMW series. Therefore, it is divided into several specific factories separately. Each specific plant creates a series. That is, a specific factory class can only create one specific product. But the BMW factory is still abstract. You need to specify a specific factory to produce cars.
4) abstract factory model era: with the increasing requirements of customers, BMW must be equipped with air conditioning. And the air conditioner must be matched to a series of cars before it can be used. So the factory began to produce BMW cars and air conditioning.
In the end, the customer just said to the salesman of BMW: I want a 523i air-conditioned car, and the salesman will give him the 523i air-conditioned car directly. Instead of creating your own 523i air-conditioned BMW
(I’m just giving an example. When it comes to BMW’s air conditioning, it’s just for example. It’s even a little bit of a drag. How can a car and an air conditioner have to be matched before they can be used.)
This is the factory model.

2、 Classification

Factory mode provides transition interface for creating objects, so as to isolate the specific process of creating objects and improve the flexibility.  
The factory model can be divided into three categories:
1) Simple factory
2) Factory method
3) Abstract factory
These three patterns are gradually abstracted from the top to the bottom, and are more general.  
GOF divides factory patterns into two categories in design patterns: factory method and abstract factory. The simple factory pattern is regarded as a special case of the factory method pattern, and they are classified into one class.

3、 Differences

Factory approach model:
An abstract product class can derive multiple concrete product classes.   
An abstract factory class can derive multiple concrete factory classes.   
Only one instance of a specific product class can be created for each specific factory class.

Abstract factory model:
Multiple abstract product classes, each abstract product class can derive multiple concrete product classes.   
An abstract factory class can derive multiple concrete factory classes.
Each specific factory class can create multiple instances of a specific product class.

difference:
The factory method pattern has only one abstract product class, while the abstract factory pattern has more than one.   
The concrete factory class of the factory method pattern can only create one instance of the concrete product class, while the abstract factory pattern can create multiple instances.
Either.  

4、 Simple factory model

Create a factory (a function or a class method) to create new objects.

Introduction to distribution description: from scratch to existence. Customers create their own BMW cars and use them.

<?php
/**
 *Car series
 *
 */
Class BWM320{
function __construct($pa) {
 
}
}
Class BMW523{
  function __construc($pb){
}
}
/**
 * 
 *Customers create their own BMW
 */
class Customer {
 
  function createBMW320(){
    return new BWM320();
  }
 
  function createBMW523(){
    return new BMW523();
  }
}

       The customer needs to know how to create a car, and the customer and the car are tightly coupled,The factory class appears. The operation details of creating BMW are put into the factory. Customers can directly use the factory creation method of the factory and pass in the desired BMW model number without knowing the details. This is the Industrial Revolution: simple factory mode

That is, we create a factory class method to create new objects. As shown in the figure:

Product category:

<?php
/**
 *Car series
 *
 */
abstract Class BWM{
  function __construct($pa) {
 
  }
}
Class BWM320 extends BWM{
  function __construct($pa) {
 
  }
}
Class BMW523 extends BWM{
  function __construc($pb){
 
  }
}

Factory class:

/**
 * 
 *Factory created car
 */
class Factory {
  static function createBMW($type){
    switch ($type) {
     case 320:
       return new BWM320();
     case 523:
       return new BMW523();
    //....
  }
}

Customer class:

/**
 * 
 *The customer obtains the car through the factory
 */
class Customer {
  private $BMW;
  function getBMW($type){
    $this¬-> BMW = Factory::createBMW($type);
  }
}

Simple factory mode is also called static factory method pattern. You can see from the renaming that this pattern must be very simple. It exists for a simple purpose: to define an interface for creating objects.

Let’s take a look at its composition
1) factory role: This is the core of this model, which contains certain business logic and judgment logic.
2) abstract product role: it is generally the parent class inherited by the specific product or the interface implemented.         
3) specific product role: the object created by the factory class is an instance of this role. It is implemented by a concrete class in Java.  

Next, we analyze the simple factory mode from the open and close principle (open to expansion; close to modification). When customers no longer meet the existing model number, they want a new type of fast car. As long as the car conforms to the contract made by abstract products, it can be used by customers as long as the factory class is informed. So for the product part, it is in line with the principle of opening and closing, but the factory part seems not very ideal,Because every time a new type of vehicle is added, the corresponding creation business logic must be added to the factory class (the method of createbmw $type needs to add a case), which is obviously against the principle of opening and closing.It can be imagined that the factory class is very passive for the addition of new products. For such factory class, we call it omnipotent or God class.  
Our example is the simplest case, but in practical application, it is likely that the product is a multi-level tree structure. Since there is only one factory class corresponding to these products in the simple factory mode, it may tire our God and our programmers: (
So the factory approach model emerged as the Savior. The factory class is defined as an interface. For each new vehicle type, the corresponding factory class implementation of the vehicle type is added. In this way, the factory design can be extended without modifying the original code.

5、 Factory approach model

The factory method pattern removes the static properties of the factory method in the simple factory pattern, so that it can be inherited by subclasses. In this way, the pressure on factory methods in the simple factory mode can be shared by different factory subclasses in the factory method pattern.  
Composition of the factory method model:

1) Abstract Factory role: This is the core of the factory method pattern and is independent of the application. Is the interface that a specific factory role must implement or a parent class that must be inherited. In Java, it is implemented by abstract classes or interfaces.  
2) specific factory role: it contains codes related to specific business logic. Object called by the application to create the corresponding product specific object.  
3) abstract product role: it is the parent class inherited by the concrete product or the interface implemented. In Java, there are generally abstract classes or interfaces to implement.  
4) specific product role: the object created by a specific factory role is an instance of this role. In Java, it is implemented by concrete classes.  
The factory method pattern replaces the “God class” in the simple factory pattern with multiple subclasses inherited from the abstract factory role. As mentioned above, this will share the pressure on the object, and make the structure more flexible – when a new product is generated, it can be used by customers without modifying any existing code as long as it is generated according to the contract provided by the abstract product role and abstract factory role. It can be seen that the structure of the role of the factory is also in line with the principle of opening and closing!  

The code is as follows:

Product category:

<?php
/**
 *Car series
 *
 */
abstract Class BWM{
  function __construct($pa) {
 
  }
}
Class BWM320 extends BWM{
  function __construct($pa) {
 
  }
}
Class BMW523 extends BWM{
  function __construc($pb){
 
  }
}

Create factory class:

/**
 *Interface to create factory
 *
 */
interface FactoryBMW { 
    function createBMW(); 
} 
/**
 * 
 *Create bwm320
 */
class FactoryBWM320 implements FactoryBMW {
  function createBMW($type){
   return new BWM320();
  }
}
/**
 * 
 *Create bwm523 car
 */
class FactoryBWM523 implements FactoryBMW {
  function createBMW($type){
   return new BMW523();
  }
}

Customer class:

/**
 * 
 *The customer gets the car
 */
class Customer {
  private $BMW;
  function getBMW($type){
   switch ($type) {
    case 320:
      $BWM320 = new FactoryBWM320();
      return $BWM320->createBMW();
    case 523:
      $BWM523 = new FactoryBWM523();
      return $BWM320->createBMW();
      //....
   }
 
 }
}

We can see that the factory method makes the number of objects multiply. When there are many kinds of products, there will be a large number of corresponding factory objects, which is not what we hope. Because if this situation can not be avoided, we can consider using the simple factory pattern and factory method pattern to reduce the factory class: that is to say, for the similar species in the product tree (generally the leaves of the tree are brothers with each other), we can use the simple factory pattern to achieve.

Summary of factory methods:

The factory method pattern seems to have wrapped the creation of objects perfectly, so that only the interfaces provided by abstract product roles are handled in the client program. Do we have to have factories all over the code? It’s not necessary. Maybe in theYou can consider using the factory approach pattern when:

1) when the client does not need to know the creation process of the object to be used.  
2) the object used by the client program may change, or it doesn’t know which specific object to use at all.

The simple factory model and factory method pattern really avoid code changes? No, In the simple factory mode, the judgment statement in the factory role should be modified when a new product is added; in the factory method mode, the judgment logic is either left in the abstract factory role, or the specific factory role is written to death in the client program (as in the above example). Moreover, the change of product object creation conditions will inevitably lead to the change of factory role.
In this case, we can use the reflection mechanism:

class Customer {
   private $BMW;
   function getBMW($type){
     $class = new reflectionclass ('factorybwm '. $type); // create a reflection class of' factorybwm ' 
     $instance = $class - > newinstanceargs(); // equivalent to instantiating 'factorybwm'. $type class 
     return $instance->createBMW();
    //Or directly 
     /**
     * $instance = new 'FactoryBWM' .$type();
     * return $instance->createBMW();
     */
  }
}

6、 Abstract factory pattern

With the increasing requirements of customers, BMW needs to be equipped with air conditioning. So the factory began to produce BMW cars and configure the required air conditioning. At this time, the factory has two series of products: BMW and air conditioner. BMW can only use the corresponding air conditioner. At this time, using a car factory and an air conditioning factory respectively can not meet our needs. We must confirm the corresponding relationship between the car and the air conditioner. Connect the air conditioner with the factory. As a result, the abstract factory pattern has emerged.

It can be said that the difference between the abstract factory pattern and the factory method pattern lies in the complexity of the object to be created. And the abstract factory pattern is the most abstract and general among the three.

The purpose of the abstract factory pattern is to provide an interface for clients to create product objects in multiple product families,In addition, the following conditions should be met when using the abstract factory pattern:

1) there are multiple product families in the system, and the system can only consume one family of products at a time.
2) products belonging to the same product family shall be used.

The roles of the abstract factory pattern (as with the factory method)

1) Abstract Factory role: This is the core of the factory method pattern and is independent of the application. Is the interface that a specific factory role must implement or a parent class that must be inherited. In Java, it is implemented by abstract classes or interfaces.  
2) specific factory role: it contains codes related to specific business logic. Object called by the application to create the corresponding product specific object.
3) abstract product role: it is the parent class inherited by the concrete product or the interface implemented.
4) specific product role: the object created by a specific factory role is an instance of this role.

Its structure is as follows:

Our example:

code:

Product category:

<?php
/**
 *Car series and models
 *
 */
abstract class BWM{
}
class BWM523 extends BWM {
}
class BWM320 extends BWM {
}
/**
 *Air conditioning
 *
 */
abstract class aircondition{
}
class airconditionBWM320 extends aircondition {
}
class airconditionBWM52 extends aircondition {
}

Create factory class:

/**
 *Interface to create factory
 *
 */
interface FactoryBMW { 
   function createBMW(); 
   function createAirC(); 
} 
/**
 * 
 *Create bwm320
 */
class FactoryBWM320 implements FactoryBMW {
  function createBMW(){
  return new BWM320();
}
Function creairc() {// air conditioning
  return new airconditionBWM320();
}
}
/**
 * 
 *Create bwm523 car
 */
class FactoryBWM523 implements FactoryBMW {
  function createBMW(){
  return new BWM523();
}
function createAirC(){
  return new airconditionBWM523();
}
}

customer:

/**
 * 
 *The customer gets the car
 */
class Customer {
  private $BMW;
  private $airC;
  function getBMW($type){
    $class = new reflectionclass ('factorybwm '. $type); // create the reflection class of person 
    $instance = $class - > newinstanceargs(); // equivalent to instantiating person class 
    $this->BMW = $instance->createBMW();
    $this->airC = $instance->createAirC();
  }
}

More about PHP related content interested readers can see this site topic: “PHP object-oriented programming introductory tutorial”, “PHP array (array) operation skills”, “PHP basic syntax introductory course”, “PHP operation and operator Usage Summary”, “PHP character string (string) Usage Summary”, “PHP + MySQL database operation introduction tutorial” and “PHP common database operation” Summary of writing skills

I hope this article will help you with PHP programming.

Recommended Today

Explain module, import and export in JavaScript

Author: Tania rascia Crazy technology house Original text:https://www.taniarascia.com/j… In the era of the Internet, websites are mainly developed with HTML and CSS. If you load JavaScript into a page, it usually provides effects and interactions in the form of small fragments. Generally, all JavaScript code is written in a file and loaded into a filescriptTag. […]