1. 盖房子需求
(1)建造房子需要打桩,砌墙,封顶;
(2)房子有各种各样,如普通房子,高楼。
2. 实现方式
(1)传统方式
/** * @Description :传统方式 * @date :2024/4/6 12:11 */ 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 house = new CommonHouse(); house.build(); } }
优点:比较好理解,简单;
缺点:把产品(房子)和创建产品的过程(建房子的流程)封装在一起,耦合性增强
(2)建造者模式
把复杂对象的建造过程抽象出来,是这个抽象过程的不同实现方法构造出不同的对象
/** * @Description :产品 * @date :2024/4/6 12:17 */ 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; } }
/** * @Description :产品创建过程 * @date :2024/4/6 12:22 */ public abstract class HouseBuilder { protected House house = new House(); //打地基 public abstract void buildBasic(); //砌墙 public abstract void buildWalls(); //封顶 public abstract void roofed(); public House buildHouse(){ return house; } }
public class CommonHouse extends HouseBuilder { @Override public void buildBasic() { System.out.println("普通房子打地基"); } @Override public void buildWalls() { System.out.println("普通房子砌墙"); } @Override public void roofed() { System.out.println("普通房子封顶"); } }
public class HighHouse extends HouseBuilder { @Override public void buildBasic() { System.out.println("高楼封顶"); } @Override public void buildWalls() { System.out.println("高楼砌墙"); } @Override public void roofed() { System.out.println("高楼屋顶"); } }
/** * @Description :指挥者决定建造哪种类型的房子 * @date :2024/4/6 12:25 */ public class HouseDirector { private HouseBuilder houseBuilder; public HouseDirector(HouseBuilder houseBuilder) { this.houseBuilder = houseBuilder; } public void setHouseBuilder(HouseBuilder houseBuilder) { this.houseBuilder = houseBuilder; } public House constructHouse(){ houseBuilder.buildBasic(); houseBuilder.buildWalls(); houseBuilder.roofed(); return houseBuilder.buildHouse(); } }
public class Client { public static void main(String[] args) { HouseDirector houseDirector = new HouseDirector(new CommonHouse()); houseDirector.constructHouse(); System.out.println("-----------------"); HighHouse highHouse = new HighHouse(); houseDirector.setHouseBuilder(highHouse); houseDirector.constructHouse(); } }
优点:增加新的具体建造者无需修改原有类的代码,指挥者对抽象建造者编程,符合开闭原则;客户端不必知道产品内部组成的细节,将产品本身与产品的创建过程解耦;