Detailed explanation of PHP design pattern builder pattern
This article mainly introduces the builder mode in the PHP design mode, and uses PHP to implement the builder mode. Interested friends can refer to it. I hope to be helpful.
Builder mode can separate the internal representation of a product from the production process of the product, so that products with different internal representations can be generated.
1. Builder mode structure diagram
2. In Builder mode Main roles
Abstract builder (Builder) role:Define an abstract interface to standardize the construction of each component of the product (that is, standardize the method implementation of the specific builder). The specified methods must include construction methods and result return methods
Concrete builder (ConcreteBuilder) role: Implement the methods defined by the abstract builder role. The specific builder is closely related to the business logic. The application will eventually create the product according to the business logic by calling the construction method implemented in this role. After the construction is completed, the built product instance will be returned through the result return method. Typically created externally by a client or an abstract factory.
Director role: The role of this role is to call the specific builder role to build the product. The director has no direct relationship with the product category. It is a concrete abstract role that talks to the product category.
Product (Product) role: The complex object created by the builder under the guidance of the director
The director role deals directly with the client, it understands the client's business logic, Split the client's request to create a product into requests for product components, and then call specific product roles to perform the build operation. It separates the client from the concrete builder.
3. Advantages and Disadvantages of Builder Pattern
Advantages of Builder Pattern: The builder pattern can well separate the implementation of an object from the related "business" logic Open, so that it can be very easy to add (or change) the implementation without changing the event logic.
Disadvantages of the Builder pattern: Modifications to the builder interface will result in modifications to all execution classes.
4. Usage scenarios and effects of Builder mode
Builder mode should be used in the following situations:
1. The product object that needs to be generated has a complex internal structure .
2. The properties of the product objects that need to be generated depend on each other, and the builder pattern can force the generation order.
3. During the object creation process, some other objects in the system will be used, which are not easy to obtain during the creation of product objects.
Using the builder pattern mainly has the following effects:
1. The use of the builder pattern allows the internal appearance of the product to change independently. Using the builder pattern eliminates the need for the client to know the details of the product's internal makeup.
2. Each Builder is relatively independent and has nothing to do with other Builders.
3. The final product built by the model is easier to control.
5. Builder mode and other modes
Abstract factory mode (abstract factory mode):In the abstract factory mode, each factory object When called, a complete product object is returned, and the client may or may not assemble these products into a larger and more complex product. The builder pattern is different. It builds a complex product piece by piece, and the assembly process of this product occurs inside the builder. The difference between the two is whether there is an assembly process and where the assembly process occurs. These two design patterns can be used together. By calling a construction role, the client indirectly calls another factory role in the abstract factory pattern. Factory mode returns parts from different product families, while Builder mode assembles them.
Strategy mode (strategy mode): The builder mode is very close to the strategy mode in structure. In fact, the builder mode is a special case of the strategy mode. The difference between the two lies in their different intentions. The builder pattern works on the client to build new objects bit by bit, while the purpose of the strategy pattern is to provide an abstract interface for the algorithm.
Builder pattern and template method pattern: After the builder pattern degenerates and loses the director role, it can develop into the template method pattern (that is, placing the algorithm implementation of the construction process in the construction role) ).
Builder pattern and composition pattern: The composition pattern describes the structure of an object tree, while the builder pattern can be used to describe the generation process of the object tree.
The above 4 points are from "Java and Patterns"
6. Builder pattern PHP example
<?php /** * 产品 * 此处仅以一个产品类中的字符串演示产品 */ class Product { /** * 产品的组成部分集合 */ private $_parts; public function __construct() { $this->_parts = array(); } public function add($part) { return array_push($this->_parts, $part); } public function show() { echo "the product include:"; array_map('printf', $this->_parts); } } /** * 抽象建造者 */ abstract class Builder { /** * 产品零件构造方法1 */ public abstract function buildPart1(); /** * 产品零件构造方法2 */ public abstract function buildPart2(); /** * 产品返还方法 */ public abstract function getResult(); } /** * 具体建造者 */ class ConcreteBuilder extends Builder { private $_product; public function __construct() { $this->_product = new Product(); } public function buildPart1() { $this->_product->add("Part1"); } public function buildPart2() { $this->_product->add("Part2"); } public function getResult() { return $this->_product; } } /** * 导演者 */ class Director { public function __construct(Builder $builder) { $builder->buildPart1(); $builder->buildPart2(); } } class Client { /** * Main program. */ public static function main() { $buidler = new ConcreteBuilder(); $director = new Director($buidler); $product = $buidler->getResult(); $product->show(); } } Client::main(); ?>
Related recommendations:
Detailed Explanation of the Adapter Pattern of PHP Design Pattern
Detailed Explanation of the Iterator Pattern of PHP Design Pattern
Detailed Explanation of the Decorator Pattern of PHP Design Pattern
The above is the detailed content of Detailed explanation of PHP design pattern builder pattern. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
