Advanced object-oriented design patterns: builder pattern
What is builder pattern?
A design pattern that separates the construction of a complex object from its representation so that the same construction process can create different representations.
Design scenario:
There is a user's UserInfo class. To create this class, you need to create the user's name, age, hobbies and other information to obtain the user's specific information. result.
Create a UserBuilder user builder class. This class encapsulates the complex creation of UserInfo's name, age, hobbies and other operations, simplifying the creation process of user classes.
This is a User class
class UserInfo { protected $_userName; protected $_userAge; protected $_userHobby; public function setUserName($userName) { $this->_userName = $userName; } public function setUserAge($userAge) { $this->_userAge = $userAge; } public function setUserHobby($userHobby) { $this->_userHobby = $userHobby; } public function getPeopleInfo() { echo "<br>这个人的名字是:" . $this->_userName . "<br>年龄为:" . $this->_userAge . "<br>爱好:" . $this->_userHobby; } }
At this time we need to obtain a user's information. The process is as follows:
$modelUser = new UserInfo(); $modelUser->setUserName('松涛'); $modelUser->setUserAge('23'); $modelUser->setUserHobby('推理小说'); $modelUser->getPeopleInfo();
The result obtained is:
The person's name is :Songtao
Age: 23
Hobbies: Mystery novels
Create a user builder class at this time
class UserBuilder { protected $_obj; public function __construct() { $this->_obj = new UserInfo(); } public function builderPeople($userInfo) { $this->_obj->setUserName($userInfo['userName']); $this->_obj->setUserAge($userInfo['userAge']); $this->_obj->setUserHobby($userInfo['userHobby']); } public function getBuliderPeopleInfo() { $this->_obj->getPeopleInfo(); } }
This will be complicated The creation process is encapsulated in the builderPeople method. The next step is to create the object:
$userArr = array( 'userName' => '松涛', 'userAge' => '23', 'userHobby' => '推理小说'); $modelUserBuilder = new UserBuilder(); $modelUserBuilder->builderPeople($userArr); $modelUserBuilder->getBuliderPeopleInfo();
The output result is:
The person’s name is: Songtao
The age is: 23
Hobby: Mystery novels
Advantages:
The builder pattern can well separate the implementation of an object from the related "business" logic, so that the event logic can be used without changing the event logic. , making it very easy to add (or change) implementations.
Disadvantages:
Modification of the builder interface will lead to modifications of all execution classes.
The builder pattern 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.
Based on the above examples, we can get the effects of the builder pattern:
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 (independent control logic).
3. The final product built by the model is easier to control.
The difference between builder mode and factory mode:
We can see that builder mode and factory mode are very similar. Overall On the other hand, the builder mode only has one more "director" role than the factory mode. In the class diagram of the builder pattern, if the director class is regarded as the client that is ultimately called, then the rest of the diagram can be regarded as a simple factory pattern.
Compared with the factory pattern, the builder pattern is generally used to create more complex objects. Because the object creation process is more complicated, the object creation process is separated to form a new class - Director kind. In other words, the factory pattern encapsulates the entire object creation process in the factory class, and the factory class provides the final product to the client; in the builder pattern, the builder class generally only provides the construction of each component in the product class. The specific construction process is handed over to the director class. The director class is responsible for configuring each component into a product according to specific rules, and then delivering the assembled product to the client.
The above is the detailed content of Advanced object-oriented design patterns: 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











OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

By mastering tracking object status, setting breakpoints, tracking exceptions and utilizing the xdebug extension, you can effectively debug PHP object-oriented programming code. 1. Track object status: Use var_dump() and print_r() to view object attributes and method values. 2. Set a breakpoint: Set a breakpoint in the development environment, and the debugger will pause when execution reaches the breakpoint, making it easier to check the object status. 3. Trace exceptions: Use try-catch blocks and getTraceAsString() to get the stack trace and message when the exception occurs. 4. Use the debugger: The xdebug_var_dump() function can inspect the contents of variables during code execution.

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

The SpringMVC framework uses the following design patterns: 1. Singleton mode: manages the Spring container; 2. Facade mode: coordinates controller, view and model interaction; 3. Strategy mode: selects a request handler based on the request; 4. Observer mode: publishes and listen for application events. These design patterns enhance the functionality and flexibility of SpringMVC, allowing developers to create efficient and maintainable applications.

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.
