Technology Sharing

Design Patterns Builder Pattern

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

The Builder Pattern in design patterns is a commonly used object creation design pattern, which is mainly used to solve the problem of building complex objects. The following is a detailed introduction to the Builder Pattern:

I. Definition

The Builder pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations. In other words, it breaks down the construction process of a complex object into a series of simple steps and allows users to create different objects by specifying the order and parameters of these steps.

2. Class Diagram and Structure

Class Diagram

In the builder mode, the following roles are usually included:

  1. Product: Represents a complex object being constructed, usually consisting of multiple components.
  2. Abstract Builder: Defines an abstract interface for creating the various components of a product object.
  3. ConcreteBuilder: Implement the Builder interface, complete the specific creation methods of each component of the complex product, and define an interface to return the final product.
  4. Director:Responsible for calling the component construction and assembly methods in the builder object to complete the creation of complex objects. It does not involve specific product information, but only decouples the client from the builder.

3. Applicable Scenarios

The builder pattern is applicable to the following scenarios:

  1. Complex object structure: When the object to be built has a complex internal structure and contains multiple properties and methods, using the builder pattern can simplify the construction process.
  2. The construction process is complex: When the object construction process involves multiple steps and the order and parameters of these steps may be different, the builder pattern can provide a clear construction process.
  3. Decoupling creation and usage: The builder pattern is a good choice when you want to separate the creation and use processes of an object so that users only need to care about the final representation of the object without having to care about the details of object creation.

4. Advantages and Disadvantages

advantage
  1. Good packaging:The construction process of complex objects is encapsulated inside the builder. The client only needs to specify the type and parameters of the construction to get the final product without knowing the details of the construction process.
  2. Good scalability: If you need to add a new build type or modify the build process, you only need to add or modify the builder class, which will not affect the client code.
  3. High flexibility: By changing the construction order or parameters of the builders, different product instances can be created flexibly.
shortcoming
  1. Increase the number of classes: Since it is necessary to create multiple classes such as builder interface, specific builder class and commander class, the number of classes in the system may increase.
  2. Difficult to modify internally: If the internal structure of the product changes, multiple builder classes may need to be modified, increasing the maintenance cost of the system.

5. Examples

In the following example, we will use the Builder pattern to design a house renovation system. We will define aHouseThe class is a complex object that contains multiple decoration components (such as ceiling, paint, floor, floor tiles, etc.). Then, we define aHouseBuilderInterface, which contains abstract methods for creating these components. Next, we create specific builder classes for each specific decoration style (such as luxurious European style, light luxury pastoral style, modern simplicity). Finally, we will pass aDirectorclass to guide the construction process, but it may not be necessary in this example because we can define the complete construction logic directly in the builder class.

However, to demonstrate the concept of the commander role, we will keep aDirectorClass, but it is only for illustration purposes, in fact the construction process can be done directly in the builder class.

  1. // 房屋类
  2. public class House {
  3. private String ceiling; // 吊顶
  4. private String paint; // 涂料
  5. private String floor; // 地板
  6. private String tiles; // 地砖
  7. // 私有构造函数
  8. private House() {}
  9. // Getter 方法
  10. public String getCeiling() {
  11. return ceiling;
  12. }
  13. public String getPaint() {
  14. return paint;
  15. }
  16. public String getFloor() {
  17. return floor;
  18. }
  19. public String getTiles() {
  20. return tiles;
  21. }
  22. // 建造者接口
  23. public interface HouseBuilder {
  24. HouseBuilder buildCeiling(String ceiling);
  25. HouseBuilder buildPaint(String paint);
  26. HouseBuilder buildFloor(String floor);
  27. HouseBuilder buildTiles(String tiles);
  28. House build();
  29. }
  30. // 豪华欧式建造者 ,注意是静态内部类
  31. public static class LuxuryEuropeanBuilder implements HouseBuilder {
  32. private House house;
  33. public LuxuryEuropeanBuilder() {
  34. this.house = new House();
  35. }
  36. @Override
  37. public HouseBuilder buildCeiling(String ceiling) {
  38. house.ceiling = "豪华欧式吊顶: " + ceiling;
  39. return this;
  40. }
  41. @Override
  42. public HouseBuilder buildPaint(String paint) {
  43. house.paint = "豪华欧式涂料: " + paint;
  44. return this;
  45. }
  46. @Override
  47. public HouseBuilder buildFloor(String floor) {
  48. house.floor = "豪华欧式地板: " + floor;
  49. return this;
  50. }
  51. @Override
  52. public HouseBuilder buildTiles(String tiles) {
  53. house.tiles = "豪华欧式地砖: " + tiles;
  54. return this;
  55. }
  56. @Override
  57. public House build() {
  58. return house;
  59. }
  60. }
  61. // ... 可以为其他风格创建类似的建造者类
  62. // 指挥者类(可选,这里主要用于展示概念)
  63. public static class Director {
  64. private HouseBuilder builder;
  65. public Director(HouseBuilder builder) {
  66. this.builder = builder;
  67. }
  68. // 这里可以添加方法来指导建造过程,但在这个例子中,我们直接在建造者中完成了所有工作
  69. public House constructHouse() {
  70. // 假设这是由指挥者指导的步骤,但在这里我们直接返回建造者的结果
  71. return builder
  72. .buildCeiling("水晶吊灯")
  73. .buildPaint("金色镶边涂料")
  74. .buildFloor("大理石地板")
  75. .buildTiles("马赛克地砖")
  76. .build();
  77. }
  78. }
  79. // 主函数,用于演示
  80. public static void main(String[] args) {
  81. HouseBuilder luxuryBuilder = new LuxuryEuropeanBuilder();
  82. // Director director = new Director(luxuryBuilder); // 如果使用指挥者
  83. House house = luxuryBuilder
  84. .buildCeiling("水晶吊灯")
  85. .buildPaint("金色镶边涂料")
  86. .buildFloor("大理石地板")
  87. .buildTiles("马赛克地砖")
  88. .build();
  89. System.out.println("Ceiling: " + house.getCeiling());
  90. System.out.println("Paint: " + house.getPaint());
  91. System.out.println("Floor: " + house.getFloor());
  92. System.out.println("Tiles: " + house.getTiles());
  93. }
  94. }

Note that in this example,DirectorThe class doesn't really add much value, since all the build logic is already encapsulated in theHouseBuilderBut in more complex applications,DirectorClasses can be used to encapsulate the order and logic of the build process, especially when the build process needs to span multiple builders.

VI. Conclusion

From the above introduction, we can see that the builder pattern has great advantages in building complex objects. It improves the encapsulation and extensibility of the code by separating the construction process from the representation, while also reducing the coupling between the client and the specific product.

If this article is helpful for your study, please like and collect it.