建造房子,有几个步骤,而且每种房子有不同的方式,首先看传统模式下的实现
传统模式
首先创建一个House抽象类,抽象了房子建造的过程方法
public abstract class AbstractHouse { public abstract void buildBasic(); public abstract void buildWalls(); public abstract void roofed(); // 建造房子的步骤 public void build(){ buildBasic(); buildWalls(); roofed(); } }
创建一个具体实现
public class CommonHouse extends AbstractHouse{ @Override public void buildBasic() { System.out.println("普通房子打地基"); } @Override public void buildWalls() { System.out.println("普通房子砌墙"); } @Override public void roofed() { System.out.println("普通房子封顶"); } }
客户端操作
public class Client { public static void main(String[] args) { CommonHouse commonHouse = new CommonHouse(); commonHouse.build(); } }
优点是比较好理解,简单易操作,设计的程序结构,过于简单,没有设计缓存层对象,程序的扩展和维护不好,也就是说,这种设计方案和创建产品的过程封装在一起,耦合性增强了
解决方法:将产品和产品的建造过程解耦=》建造者模式
首先看看这张url图,看不懂的请自行百度学习。
代码实现
首先创建一个产品类
public class House { private String basic; private String wall; private String roofed; public String getBasic() { return basic; } public void setBasic(String basic) { this.basic = basic; } public String getWall() { return wall; } public void setWall(String wall) { this.wall = wall; } public String getRoofed() { return roofed; } public void setRoofed(String roofed) { this.roofed = roofed; } }
创建一个建造者
public abstract class HouseBuilder { protected House house = new House(); public abstract void builderBasic(); public abstract void builderWalls(); public abstract void builderRoofed(); public House build(){ return house; } }
创建具体建造者
public class CommonHouse extends HouseBuilder{ @Override public void builderBasic() { System.out.println("普通房子打地基"); } @Override public void builderWalls() { System.out.println("普通房子砌墙"); } @Override public void builderRoofed() { System.out.println("普通房子的屋顶"); } }
public class HighBuilding extends HouseBuilder{ @Override public void builderBasic() { System.out.println("高楼打地基100米"); } @Override public void builderWalls() { System.out.println("高楼砌墙20m"); } @Override public void builderRoofed() { System.out.println("高楼的屋顶"); } }
创建指挥者
public class HouseDirector { private HouseBuilder houseBuilder; // 构造器传入 public HouseDirector(HouseBuilder houseBuilder) { this.houseBuilder = houseBuilder; } public HouseBuilder getHouseBuilder() { return houseBuilder; } // set方法传入 public void setHouseBuilder(HouseBuilder houseBuilder) { this.houseBuilder = houseBuilder; } // 如何处理建造房子的流程,交给指挥者 public House constractHouse(){ houseBuilder.builderBasic(); houseBuilder.builderWalls(); houseBuilder.builderRoofed(); return houseBuilder.build(); } }
客户端操作
public class Cilent { public static void main(String[] args) { // 普通房子 CommonHouse commonHouse = new CommonHouse(); // 准备创建房子的指挥者 HouseDirector houseDirector = new HouseDirector(commonHouse); // 返回产品 House house = houseDirector.constractHouse(); } }