Builder模式¶
Builder模式是一种常用的软件设计模式,用于将一个复杂对象的构建过程与其表示分离,使得同样的构建过程可以创建不同的表示。这种模式主要用于需要生成各种属性复杂且数量众多的对象时。通过Builder模式,我们可以逐步构建一个复杂对象,而不需要将所有的构建逻辑都放在一个构造函数里,这样可以提高代码的可读性和可维护性。
Java¶
// Product
class Car {
private int wheels;
private String color;
public void setWheels(int wheels) {
this.wheels = wheels;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Car{" +
"wheels=" + wheels +
", color='" + color + '\'' +
'}';
}
}
// Builder
interface CarBuilder {
CarBuilder setWheels(int wheels);
CarBuilder setColor(String color);
Car build();
}
// ConcreteBuilder
class ConcreteCarBuilder implements CarBuilder {
private Car car;
public ConcreteCarBuilder() {
this.car = new Car();
}
@Override
public CarBuilder setWheels(int wheels) {
car.setWheels(wheels);
return this;
}
@Override
public CarBuilder setColor(String color) {
car.setColor(color);
return this;
}
@Override
public Car build() {
return car;
}
}
// Usage
public class BuilderExample {
public static void main(String[] args) {
Car car = new ConcreteCarBuilder()
.setWheels(4)
.setColor("Red")
.build();
System.out.println(car);
}
}
Golang¶
package main
import "fmt"
// Product
type Car struct {
wheels int
color string
}
// Builder
type CarBuilder interface {
SetWheels(wheels int) CarBuilder
SetColor(color string) CarBuilder
Build() Car
}
// ConcreteBuilder
type carBuilder struct {
car Car
}
func NewCarBuilder() CarBuilder {
return &carBuilder{}
}
func (b *carBuilder) SetWheels(wheels int) CarBuilder {
b.car.wheels = wheels
return b
}
func (b *carBuilder) SetColor(color string) CarBuilder {
b.car.color = color
return b
}
func (b *carBuilder) Build() Car {
return b.car
}
// Usage
func main() {
builder := NewCarBuilder()
car := builder.SetWheels(4).SetColor("Blue").Build()
fmt.Printf("%+v\n", car)
}
Python¶
# Product
class Car:
def __init__(self):
self.wheels = None
self.color = None
def __str__(self):
return f"Car(wheels={self.wheels}, color={self.color})"
# Builder
class CarBuilder:
def set_wheels(self, wheels):
self.car.wheels = wheels
return self
def set_color(self, color):
self.car.color = color
return self
def build(self):
return self.car
# ConcreteBuilder
class ConcreteCarBuilder(CarBuilder):
def __init__(self):
self.car = Car()
# Usage
if __name__ == "__main__":
builder = ConcreteCarBuilder()
car = builder.set_wheels(4).set_color("Green").build()
print(car)