本文聊一下建造者模式。
3、建造者模式
- 分离了对象子组件的单独构造(由Builder来负责)和装配(由Director负责)。从而可以构造出复杂的对象。这个模式适用于:对象的构建过程复杂。
- 由于实现了构建和装配的解耦,不同的构造器相同的装配也可以构造出不同的对象;相同的构造器不同的装配顺序也可以构造出不同的对象。(实现了构建算法、装配算法的解耦)
代码根据构建一辆车来展示:
- 构建一辆车需要轮子和引擎
- 构建器和装配器接口与实现
- 客户端调用
1、构建一辆车需要轮子和引擎
public class Car {
private Engine engine; //发动机
private Wheel wheel; //轮子
public Car(Engine engine, Wheel wheel) {
this.engine = engine;
this.wheel = wheel;
}
public Car() {
}
public Engine getEngine() {
return engine;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public Wheel getWheel() {
return wheel;
}
public void setWheel(Wheel wheel) {
this.wheel = wheel;
}
}
class Wheel{
private String name;
public Wheel(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Engine{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Engine(String name) {
this.name = name;
}
}
2、构建器和装配器接口与实现
public interface CarBuilder {
Engine builderEngine();
Wheel builderWheel();
}
public interface CarDirector {
/**
* 组装汽车对象
* @return
*/
Car directCar();
}
public class TqqCarBuilder implements CarBuilder{
@Override
public Engine builderEngine() {
return new Engine("tqq牌发动机");
}
@Override
public Wheel builderWheel() {
return new Wheel("tqq牌车轮子");
}
}
public class TqqCarDirector implements CarDirector{
private CarBuilder builder;
public TqqCarDirector(CarBuilder builder) {
this.builder = builder;
}
@Override
public Car directCar() {
Engine engine = builder.builderEngine();
Wheel wheel = builder.builderWheel();
Car car = new Car();
car.setEngine(engine);
car.setWheel(wheel);
return car;
}
}
3、客户端调用
public class Client {
public static void main(String[] args) {
TqqCarDirector director = new TqqCarDirector(new TqqCarBuilder());
Car car = director.directCar();
System.out.println(car.getEngine().getName());
}
}
开发中常见的场景
- StringBuilder类的append方法
- SQL中的PreparedStatement