PHP design pattern (3) builder mode

Time:2020-11-21

This paper describes the PHP design pattern: Builder mode builder. For your reference, the details are as follows:

1. Overview

In the process of software development, when a “complex object” is created, the object is composed of sub objects of certain parts with a certain algorithm. Due to the change of requirements, each part of the complex object often faces drastic changes, but the algorithm combining them together is relatively stable.

       Example 1: buy KFC

A typical children’s meal consists of a staple food, a complementary food, a drink and a toy (such as hamburger, fried chicken, coke and toy car). These can be different in different children’s meals, but the process of combining them into children’s meals is the same.

       clientCustomer, if you want to buy a set of set meal (including hamburger, coke and French fries), you can choose from No.1 and No.2.
       Mentor role: Cashier. Know what kind of set meal the customer wants to buy and tell the restaurant staff to prepare the set meal.
       Builder role: restaurant staff. According to the cashier’s requirements to prepare the specific set meal, respectively put hamburger, coke, French fries, etc.
       Product roleFor the final set meal, everything is on the same plate.

       Example 2: calculate salary: the calculation of salary is generally: base salary + bonus tax. However, the basic salary is divided into three levels: 8000 in the first level, 6000 in the second level and 4000 in the third level. According to the different positions, the bonus payment is also different. For the management and daily affairs processing post (Class A), the bonus is calculated according to the evaluation score between leaders and colleagues every month, while for the sales post (category B), the Commission is paid according to the sales volume. The tax is calculated according to the amount of bonus and base salary. It can be seen from this that the calculation method of the salary is a relatively stable construction algorithm, but different algorithms will be generated for each part of the salary according to different situations. How to separate the client from the calculation methods of the base salary, bonus and tax with great changes is also suitable for the builder mode.

2. Problems

How can we deal with this change, and how to provide a “encapsulation mechanism” to isolate the changes of “various parts of complex objects”, so as to keep the “stable construction algorithm” in the system unchanged with the change of requirements?

3. Solutions

Builder pattern: separates the construction of a complex object from its representation so that different representations can be created in the same build process.

4. Applicability

Use the builder pattern in the following cases

When the algorithm for creating a complex object should be independent of its components and how they are assembled.

When the construction process must allow different representations of the constructed object.

5. Structure

The structure of this mode is shown in the figure above on the following page.

6. Composition of construction mode

· Abstract builder role: specify abstract interface for each part of creating a product object to standardize the construction of each component of product object. Generally speaking, this role specifies which parts of a complex object are to be created, and does not involve the creation of specific object parts.

· concrete builder

1) The interface of builder is implemented to construct and assemble various parts of the product. That is to realize the method of abstract builder role builder.

2) Define and define the representation it creates, that is, to materialize the creation of various parts of complex objects for different business logic

3) Provides an interface to retrieve products

4) To construct an object using builder interface is to create a product instance under the call of the instructor

Director: call the specific builder role to create parts of the product object. The director does not involve the information of specific product class, and the real information of specific product is the specific builder object. It is only responsible for ensuring that all parts of an object are created completely or in a certain order.

Product roleComplex objects in construction. It contains the classes that define the components, including the interfaces that assemble these components into products.

7. Effect

The main effects of builder mode are as follows:

1) it allows you to change the internal representation of a product, and the builder object provides the director with an abstract interface to construct the product. This interface allows the generator to hide the representation and internal structure of the product. It also hides how the product is assembled. Because a product is constructed through an abstract interface, all you have to do to change the internal representation of the product is to define a new generator.

2) It separates the construction code from the presentation code, and improves the modularity of the object by encapsulating the creation and representation of a complex object. The customer does not need to know all the information about the classes that define the internal structure of the product; these classes do not appear in the builder interface. Each concrete builder contains all the code to create and assemble a specific product. This code only needs to be written once; then different directors can reuse it to build different products based on the same set of parts.

3) it enables you to control the construction process more finely. Unlike the creation mode of building products in one go, builder mode constructs products step by step under the control of guiders. Only when the product is complete does the director retrieve it from the generator. Therefore, the builder interface can better reflect the product construction process than other creation patterns. This allows you to have more fine-grained control over the build process, which in turn allows you to control the internal structure of the resulting product.

8. Realize:

Instructor: Cashier

<?php
 /**
 *Instructor: Cashier
 *
 */
 class DirectorCashier
 {
 /**
  *Food returned by cashier restaurant staff
  *
  */
 public function buildFood(Builder $builder) {
  $builder->buildPart1();
  $builder->buildPart2();
 }
 }

Abstract Builder:

/**
 *Abstract builder
 *
 */
 abstract class Builder
 {
 /**
  *Create the first part of the product
   */
 public abstract function buildPart1();
 
 /**
  * 
  *Create the second part of the product
   */
 public abstract function buildPart2();
 
 /**
  * 
  *Return to product
   */
 public abstract function getProduct();
 }

Specific builder class:

/**
 *The specific builder class: restaurant staff, the returned package is: two hamburgers + one drink
 *
 */
 class ConcreteBuilder1 extends Builder
 {
 protected $_ Product = null; // product object
 function __construct(){
  $this->_product = new Product();
 }
 
 /**
  *Create the first part of the product: hamburger = 2
   */
 public function buildPart1()
 {
  $this->_product->add('Hamburger',2);
 }
 /**
  * 
  *Create the second part of the product:
   */
 public function buildPart2()
 {
  $this->_product->add('Drink', 1);
 }
 /**
  *Return product object:
  * 
  */
 public function getProduct() {
  return $this->_product;
 }
 }
/**
 *Specific Builder: restaurant staff, 1 hamburger + 2 drinks
 *
 */
 class ConcreteBuilder2 extends Builder
 {
 protected $_ Product = null; // product object
 function __construct(){
  $this->_product = new Product();
 }
 
 /**
  *Creating the first part of the product: hamburger
   */
 public function buildPart1()
 {
  $this->_product->add('Hamburger', 1);
 }
 /**
  * 
  *Create the second part of the product: drink = 2
   */
 public function buildPart2()
 {
  $this->_product->add('Drink', 2);
 }
 /**
  *Return product object:
  * 
  */
 public function getProduct() {
  return $this->_product;
 }
 }

Product category:

/**
 *Products
 */
 class Product
 {
 public $products = array();
 /**
  *Add specific products
  */
 public function add($name, $value) {
  $this->products[$name] = $value;
 }
 /**
  *Show customers products
  */
 public function showToClient()
 {
  foreach ($this->products as $key => $v) {
  echo $key , '=' , $v ,'<br>';
  }
 }
 }

Client program:

//Client program
 class Client
 {
 /**
  *Customer purchase package
  *
  */
 public function buy($type) {
  //Director, cashier
  $director = new DirectorCashier(); 
  //Restaurant staff, cashier
     $class = new ReflectionClass('ConcreteBuilder' .$type );
     $concreteBuilder = $class->newInstanceArgs();
     //Cashiers combine food returned by employees
     $director->buildFood($concreteBuilder);
     //Return to customer
     $concreteBuilder->getProduct()->showToClient();
 }
 }
 //Testing
 ini_set('display_errors', 'On');
 $c = new Client();
 $C - > buy (1); // buy package 1
 $C - > buy (2); // purchase package 1

9. Advantages of builder model

First of all, the encapsulation of the builder pattern is very good. Using builder mode can effectively encapsulate changes. In the scenario of using builder mode, the general product class and builder class are relatively stable. Therefore, encapsulating the main business logic in the director class can achieve better stability on the whole.

Second, the builder pattern is easy to extend. If there is a new requirement, it can be completed by implementing a new builder class. Basically, there is no need to modify the code that has been tested before, so there will be no risk to the original function.

10. Difference between builder model and factory model

We can see that the builder mode is very similar to the factory mode. On the whole, the builder mode only has one more “director” role than the factory mode. In the class diagram of builder mode, if the director class is regarded as the client of the final call, the rest of the diagram can be regarded as a simple factory pattern.

Compared with the factory pattern, builder pattern is usually used to create more complex objects. Because the process of creating objects is more complicated, the process of creating objects is separated to form a new class director class. In other words, the factory mode encapsulates all the creation process of objects in the factory class, and the factory class provides the final product to the client; in the builder mode, the builder class generally only provides the construction of each component in the product class, and delivers the specific construction process to the demonstration class. The director class is responsible for building each component into a product according to specific rules, and then delivering the finished product to the client.

11. Summary

The builder model is similar to the factory model, they are both builder mode, and the applicable scenarios are very similar. Generally speaking, if the construction of a product is complex, use the factory model; if the construction of the product is more complex, use the builder mode.

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. […]