建造者模式
字数: 0

基本概念

Builder Pattern: (GoF Definition) Separate the construction of a complex object from its representation so that the same construction processes can create different representations
  • create a complex object step by step
  • promote encapsulation by hiding the details of the construction process
notion image
通常情况下, 大部分参数都没有使用(例如,只有少数房子有游泳池), 这使得构造函数十分不简洁
notion image
 
✔️
建议将对象构造代码从产品类中抽取出。
notion image
💡
如果属性设置顺序不同会产生不同效果,或者建造者类太复杂,可使用 Director 来指挥,它是可选角色。

实现代码

建造者

Builder:一个接口或抽象类,定义了创建对象的抽象方法。

具体建造者

Concrete Builder:生成器接口的实现类,构建实际对象,设置属性等。

产品

Product:最终构建的对象。

测试类

Q & A

What are the drawbacks/pitfalls associated with the builder pattern?
  • You may need to duplicate some portion of the code.
  • It is not suitable if you want to deal with mutable objects (which can be modified later).

具体应用

Java StringBuilder

🤖
Java String 类的字符串(value 在栈中的引用地址)是不可变的。
 
以上实质上是开辟了 2 个内存空间,var1 由原来指向 “Apple” 变为指向 “Banana” 。
notion image
notion image
 
 
  • == 指两个对象的引用相同
  • equals() 指两个对象的值相等
🤖
字符串需要动态创建,提高内存使用效率时,可以引入 StringBuilder
notion image

实际上,String 类的两个字符串通过 “+” 连接时,底层实际是先初始化一个 StringBuilder 对象,然后调用 append 方法来连接,最后通过 toString() 方法返回拼接后的字符串。
 
2023 - 2026