private Engine engine; private Tyre tyre; private Seat seat; public void intro() { this.engine.intro(); this.tyre.intro(); this.seat.intro(); }
public Engine getEngine() { return engine; }
public void setEngine(Engine engine) { this.engine = engine; }
public Tyre getTyre() { return tyre; }
public void setTyre(Tyre tyre) { this.tyre = tyre; }
public Seat getSeat() { return seat; }
public void setSeat(Seat seat) { this.seat = seat; } }
class Engine {
public void intro() { System.out.println("开得快"); } }
class Tyre { public void intro() { System.out.println("耐磨防滑"); } }
class Seat { public void intro() { System.out.println("坐得舒适"); } }
Car 类的实例就是一个复合对象。
未使用建造者模式时,客户端调用如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public class Client {
public static void main(String[] args) { // 创建组装部件 Engine engine = new Engine(); Tyre tyre = new Tyre(); Seat seat = new Seat(); // 组装 Car car = new Car(); car.setEngine(engine); car.setTyre(tyre); car.setSeat(seat); car.intro(); } }
class MyCarDirector implements CarDirector { private CarBuilder carBuilder; public MyCarDirector(CarBuilder carBuilder) { this.carBuilder = carBuilder; }
@Override public Car directCar() { Engine engine = this.carBuilder.buildEngine(); Tyre tyre = this.carBuilder.buildTyre(); Seat seat = this.carBuilder.buildSeat(); // 装配 Car car = new Car(); car.setEngine(engine); car.setTyre(tyre); car.setSeat(seat); return car; } }
通过 directCar 方法,隐藏复合对象(Car 实例)的创建过程。
客户端:
1 2 3 4 5 6 7 8 9 10 11 12
public class Client {
public static void main(String[] args) { CarDirector director = new MyCarDirector(new MyCarBuilder()); Car car = director.directCar(); car.intro(); } }
现在,客户端代码变得简洁了。因为建造者模式遵循了依赖倒转原则,我们只要将客户端的 Builder 或 Director 替换不同的接口实现类(多态),就能体现出代码灵活性了。