建造者模式
建造者模式适用场景:
建造一个复杂的对象适用,将构建对象的过程分开,每个类单独构造对象的一部分,最后组装起来,返回我们需要的对象。
下面的例子主要讲解构造一个飞船
Demo:
//要获得的对象,但是各个组件要拆分开,让对应的类去实现
class AirShip {
private OrbitaModule orbitaModule;//轨道舱
private Engine engine; //发动机
private EscapeTower escapeTower;//逃逸塔
public OrbitaModule getOrbitaModule() {
return orbitaModule;
}
public void setOrbitaModule(OrbitaModule orbitaModule) {
this.orbitaModule = orbitaModule;
}
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;
}
}
class OrbitaModule{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public OrbitaModule(String name) {
super();
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) {
super();
this.name = name;
}
}
class EscapeTower{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EscapeTower(String name) {
super();
this.name = name;
}
}
public interface AirShipBuilder {
Engine builderEngine();
OrbitaModule builderOrbitaModule();
EscapeTower builderEscapeTower();
}
//创建返回对象的接口
public interface AirShipDirector {
AirShip directAirShip();
}
//组装对象的实现类
public class AirShipBuilderImpl implements AirShipBuilder{
@Override
public Engine builderEngine() {
System.out.println("构建发动机");
return new Engine("发动机");
}
@Override
public OrbitaModule builderOrbitaModule() {
System.out.println("构建逃逸塔");
return new OrbitaModule("逃逸塔");
}
@Override
public EscapeTower builderEscapeTower() {
System.out.println("构建轨道舱");
return new EscapeTower("轨道舱");
}
}
//返回对象的实现类
public class AirShipDirectorImpl implements AirShipDirector{
//创建一个构造组件的接口对象,此处可以使用工厂模式进行修改
private AirShipBuilder airShipBuilder;
public AirShipDirectorImpl(AirShipBuilder airShipBuilder) {
super();
this.airShipBuilder = airShipBuilder;
}
@Override
public AirShip directAirShip() {
Engine builderEngine = airShipBuilder.builderEngine();
OrbitaModule builderOrbitaModule = airShipBuilder.builderOrbitaModule();
EscapeTower builderEscapeTower = airShipBuilder.builderEscapeTower();
AirShip ship = new AirShip();
ship.setEngine(builderEngine);
ship.setEscapeTower(builderEscapeTower);
ship.setEscapeTower(builderEscapeTower);
return ship;
}
}
//客户端调用
public class Client {
public static void main(String[] args) {
AirShipDirector airShipDirector = new AirShipDirectorImpl(new AirShipBuilderImpl());
AirShip directAirShip = airShipDirector.directAirShip();
System.out.println(directAirShip);
}
}
建造者模式主要就是将建造飞船的过程简单的拆分开,让构建飞船的不同的组件让不同的类去完成,此处就可以和工厂模式和单例模式相结合,让开发变得更加清晰。