建造者模式也叫生成器模式,是一种对象创建型模式,用来隐藏复合对象的创建过程,它把复合对象的创建过程加以抽象,通过子类继承或重载的方式,动态的创建具有复合属性的对象。
应用场景:
-对象的创建:Builder模式是为对象的创建而设计的模式
-创建的是一个复合对象:被创建的对象为一个具有复合属性的复合对象
-关注对象创建的各部分的创建过程:不同的工厂(这里指builder生成器)对产品属性有不同的创建方法
复合属性的对象(即要创建的对象):
public class House { private String floor; private String wall; private String proof; 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 getProof() { return proof; } public void setProof(String proof) { this.proof = proof; } }
public interface HouseBuilder { public void makeFloor(); public void makeWall(); public void makeProof(); public House getHouse(); }
具体创建者实现类1:
public class ApartmentBuilder implements HouseBuilder { private House house = new House(); @Override public House getHouse() { return house; } @Override public void makeFloor() { house.setFloor("Apartment --> Floor"); } @Override public void makeWall() { house.setWall("Apartment --> Wall"); } @Override public void makeProof() { house.setProof("Apartment --> Proof"); } }
public class VillaBuilder implements HouseBuilder { private House house = new House(); @Override public void makeFloor() { house.setFloor("Villa --> Floor"); } @Override public void makeWall() { house.setWall("Villa --> Wall"); } @Override public void makeProof() { house.setProof("Villa --> Proof"); } @Override public House getHouse() { return house; } }
设计者类:
public class HouseDirector { public void makeHouse(HouseBuilder builder) { builder.makeFloor(); builder.makeProof(); builder.makeWall(); } }
客户端调用类:
public class ClientApp { public static void main(String[] args) { // HouseBuilder builder = new ApartmentBuilder(); HouseBuilder builder = new VillaBuilder(); HouseDirector director = new HouseDirector(); director.makeHouse(builder); House house = builder.getHouse(); System.out.println(house.getFloor()); System.out.println(house.getProof()); System.out.println(house.getWall()); } }
原文地址:http://blog.csdn.net/rushuiwushi/article/details/40748689