1.定义
Builder模式也叫建造者模式或者生成器模式,是由GOF提出的23种设计模式中的一种。
Builder模式是一种对象创建型模式之一,用来隐藏复合对象的创建过程,它把复合对象的创建过程加以抽象,通过子类继承和重载的方式,动态地创建具有复合属性的对象。
2.结构图
3.应用场景
- 对象的创建:Builder模式是为对象的创建而设计的模式。
- 创建的是一个复合对象:被创建的对象为一个具有复合属性的复合对象。
- 关注对象创建的各部分的创建过程:不同的工厂(这里指Builder生成器)对产品属性有不同的创建方法。
4.代码演示
package test.com.builder; /* * product--产品类 */ public class House { private String floor; private String wall; private String housetop; public String getFloor() { return floor; } public void setFloor(String floor) { this.floor = floor; } public String getWall() { return wall; } public void setWall(String wall) { this.wall = wall; } public String getHousetop() { return housetop; } public void setHousetop(String housetop) { this.housetop = housetop; } }
package test.com.builder; /* * Builder--抽象建造者 */ public interface HouseBuilder { public void makeFloor(); public void makeWall(); public void makeHousetop(); public House getHouse(); }
package test.com.builder; /* * concrete builder--具体建造者 */ public class PingfangBuilder implements HouseBuilder { private House house = new House(); @Override public void makeFloor() { house.setFloor("平房-->地板"); } @Override public void makeWall() { house.setWall("平房-->墙"); } @Override public void makeHousetop() { house.setHousetop("平房-->房顶"); } public House getHouse() { return house; } }
package test.com.builder; /* * director--指导者 */ public class DirectorBuilder { //first private HouseBuilder houseBuilder; public DirectorBuilder(HouseBuilder houseBuilder) { this.houseBuilder = houseBuilder; } public void makeHouse() { this.houseBuilder.makeFloor(); this.houseBuilder.makeWall(); this.houseBuilder.makeHousetop(); } //second public DirectorBuilder() { } public void makeHouse(HouseBuilder houseBuilder) { houseBuilder.makeFloor(); houseBuilder.makeWall(); houseBuilder.makeHousetop(); } }
package test.com.builder; /* * 测试 */ public class MainClass { public static void main(String[] args) { //由工程队建造 HouseBuilder hb = new PingfangBuilder(); hb.makeFloor(); hb.makeHousetop(); hb.makeWall(); House h = hb.getHouse(); System.out.println(h.getFloor());//平房-->地板 System.out.println(h.getHousetop());//平房-->房顶 System.out.println(h.getWall());//平房-->墙 //由设计者调用,工程队创建 HouseBuilder hb2 = new PingfangBuilder(); DirectorBuilder db = new DirectorBuilder(hb2); db.makeHouse(); House h2 = hb2.getHouse(); System.out.println(h2.getFloor());//平房-->地板 System.out.println(h2.getHousetop());//平房-->房顶 System.out.println(h2.getWall());//平房-->墙 //由设计者调用,工程队创建 HouseBuilder hb3 = new PingfangBuilder(); DirectorBuilder db3 = new DirectorBuilder(); db3.makeHouse(hb3); House h3 = hb.getHouse(); System.out.println(h3.getFloor());//平房-->地板 System.out.println(h3.getHousetop());//平房-->房顶 System.out.println(h3.getWall());//平房-->墙 } }