- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 366字
- 2021-06-25 20:52:34
Builder pattern
The builder pattern serves the same purpose as the other creational patterns, but it does so in a different way and for different reasons. When developing complex applications, the code tends to become more complex. Classes tend to encapsulate more functionality and, at the same time, class structures become more complex. As the functionality grows, more scenarios need to be covered and, for these, different representations of classes are required.
When we have a complex class that we need to instantiate to different objects with different structures or different internal states, we can use separate classes to encapsulate the instantiation logic. These classes are called builders. Each time we need objects from the same class with a different structure, we can create another builder to create such instances.
The same concept can be used not only for classes for which we need different representations but also for complex objects composed of other objects.
Creating builder classes to encapsulate the logic to instantiate complex objects is consistent with the single responsibility principle and with the open/closed principle. The logic to instantiate a complex object is moved to a separate Builder class. When we need objects with different structures, we can add new builder classes, so the code is closed for modification and open for extension, as shown in the diagram:

The following classes are involved in the builder pattern:
- Product: The class whose objects we have to build. It is a complex or a composite object of which we need different representations.
- Builder: The abstract class or interface which declares the parts from which the product is built. Its role is to expose only the functionality required to build the Product, hiding the rest of the Product functionality; it decouples the Product from the higher-level class that builds it.
- ConcreteBuilder: A concrete builder that implements the methods declared in the Builder interface. In addition to the methods declared in the Builder abstract class, it has a getResult method that returns the built product.
- Director: A class that directs how the object is built. In some variants of the builder pattern this class is removed, its role being taken by either the client or the builder.
- 精通Nginx(第2版)
- Spring Boot開發(fā)與測試實戰(zhàn)
- Debian 7:System Administration Best Practices
- PyQt從入門到精通
- DevOps入門與實踐
- 數據結構簡明教程(第2版)微課版
- JS全書:JavaScript Web前端開發(fā)指南
- Teaching with Google Classroom
- 51單片機C語言開發(fā)教程
- Internet of Things with ESP8266
- 小型編譯器設計實踐
- Python 3.7從入門到精通(視頻教學版)
- SQL Server 2008 R2數據庫技術及應用(第3版)
- 軟件測試綜合技術
- 嵌入式Linux C語言程序設計基礎教程