场景
- 需要建造一个复杂的产品
- 实际开发中,我们所需要的对象构建起来非常复杂,有很多步骤需要处理
本质
- 分离了对象子组件的单独构造和装配。
- 实现了构造和装配的解耦。构建与装配的不同组合可以构造出不同的对象,实现了更好的复用。
代码示意
需要构建的对象AirShip:持有子组件的引用
public class AirShip {
private OrbitalModule orbitalModule;//轨道舱
private Engine engine;//引擎
private EscapeTower escapeTower;//逃逸塔
AirShip(OrbitalModule orbitalModule, Engine engine, EscapeTower escapeTower) {
this.orbitalModule = orbitalModule;
this.engine = engine;
this.escapeTower = escapeTower;
}
/**
* 自己定义其它方法
*/
public void customMethod() {
}
OrbitalModule getOrbitalModule() {
return orbitalModule;
}
public void setOrbitalModule(OrbitalModule orbitalModule) {
this.orbitalModule = orbitalModule;
}
public Engine getEngine() {
return engine;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public EscapeTower getEscapeTower() {
return escapeTower;
}
public void setEscapeTower(EscapeTower escapeTower) {
this.escapeTower = escapeTower;
}
}
定义Builder接口:
public interface AirShipBuilder {
OrbitalModule buildOrbitalModule();
Engine buildEngine();
EscapeTower buildEscapeTower();
}
定义Director接口:
public interface AirShipDirector {
AirShip directAirShip();
}
分别定义它们的实现类:
public class MyAirShipBuilder implements AirShipBuilder {
@Override
public OrbitalModule buildOrbitalModule() {
return new OrbitalModule();
}
@Override
public Engine buildEngine() {
return new Engine();
}
@Override
public EscapeTower buildEscapeTower() {
return new EscapeTower();
}
}
public class MyAirShipDirector implements AirShipDirector {
//持有构建对象的引用
private MyAirShipBuilder builder;
MyAirShipDirector(MyAirShipBuilder builder) {
this.builder = builder;
}
@Override
public AirShip directAirShip() {
OrbitalModule orbitalModule = builder.buildOrbitalModule();
Engine engine = builder.buildEngine();
EscapeTower escapeTower = builder.buildEscapeTower();
return new AirShip(orbitalModule, engine, escapeTower);
}
}
构建对象:
public class Client {
public static void main(String[] args) {
AirShipDirector director = new MyAirShipDirector(new MyAirShipBuilder());
AirShip airShip = director.directAirShip();
}
}