建造者模式 建造者模式適用場景: 建造一個複雜的對象適用,將構建對象的過程分開,每個類單獨構造對象的一部分,最後組裝起來,返回我們需要的對象。 下麵的例子主要講解構造一個飛船 Demo: //要獲得的對象,但是各個組件要拆分開,讓對應的類去實現 class AirShip { private Orb ...
建造者模式
建造者模式適用場景:
建造一個複雜的對象適用,將構建對象的過程分開,每個類單獨構造對象的一部分,最後組裝起來,返回我們需要的對象。
下麵的例子主要講解構造一個飛船
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);
}
}
建造者模式主要就是將建造飛船的過程簡單的拆分開,讓構建飛船的不同的組件讓不同的類去完成,此處就可以和工廠模式和單例模式相結合,讓開發變得更加清晰。