标签:null 指定 创建 ted rect com dingding 角色 产品
建造者模式属于创造型模式,它是将复杂对象的建造过程抽象出来,使这个抽象过程的不同实现方法可以构造出不同表现的对象。
举例:
普通房子和高楼,两者都很难建造,但也有相似点:打地基、砌墙、盖屋顶。
普通房子的地基5m,墙10cm;高楼的地基100m,墙20cm。
/**
* @author dingding
* 产品对象
*/
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;
}
}
/**
* @author dingding
* 抽象建造者
*/
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;
}
}
/**
* @author dingding
* 具体构造者1
*/
public class CommonHouse extends HouseBuilder {
@Override
public void buildBasic() {
System.out.println(" 普通房子打地基5米 ");
}
@Override
public void buildWalls() {
System.out.println(" 普通房子砌墙10cm ");
}
@Override
public void roofed() {
System.out.println(" 普通房子屋顶 ");
}
}
/**
* @author dingding 具体构造者2
*/
public class HignHouse extends HouseBuilder {
@Override
public void buildBasic() {
System.out.println(" 高楼的打地基100米 ");
}
@Override
public void buildWalls() {
System.out.println(" 高楼的砌墙20cm ");
}
@Override
public void roofed() {
System.out.println(" 高楼的透明屋顶 ");
}
}
/**
* @author dingding
* 指挥者
*/
public class HouseDirector {
HouseBuilder houseBuilder = null;
public HouseDirector(HouseBuilder houseBuilder) {
this.houseBuilder = houseBuilder;
}
public void setHouseBuilder(HouseBuilder houseBuilder) {
this.houseBuilder = houseBuilder;
}
public House constructHouse() {
houseBuilder.buildBasic();
houseBuilder.buildWalls();
houseBuilder.buildHouse();
return houseBuilder.buildHouse();
}
}
/**
* @author dingding
* 客户端
*/
public class Client {
public static void main(String[] args) {
CommonHouse commonHouse = new CommonHouse();
HouseDirector houseDirector = new HouseDirector(commonHouse);
House house = houseDirector.constructHouse();
System.out.println("----------------------");
HignHouse hignHouse = new HignHouse();
houseDirector.setHouseBuilder(hignHouse);
house = houseDirector.constructHouse();
}
}
标签:null 指定 创建 ted rect com dingding 角色 产品
原文地址:https://www.cnblogs.com/lfdingye/p/11625896.html