Home Backend Development PHP Tutorial Detailed explanation of PHP design pattern builder pattern

Detailed explanation of PHP design pattern builder pattern

Jan 05, 2018 pm 05:51 PM
php Design Patterns

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(&#39;printf&#39;, $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();
?>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles