建造者模式_设计模式_java
原创
©著作权归作者所有:来自51CTO博客作者959_1x的原创作品,请联系作者获取转载授权,否则将追究法律责任
建造者模式:
顾名思义:是创造型模式
而最重要的是解耦来获得建造者和用户之间的依赖关系
JDK中的StringBuldder就是用的建造者设计模式
类图:
1.House.java
public class House {
private String baise;
private String wall;
private String roofed;
public String getBaise() {
return baise;
}
public void setBaise(String baise) {
this.baise = baise;
}
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;
}
}
抽象的建造者
2.HouseBuild.java
public abstract class HouseBuilder {
protected House house = new House();
//建造的流程
public abstract void buildBasic();
public abstract void buildWoll();
public abstract void buildroofed();
//建造房子
public House buildHouse() {
return house;
}
}
具体的建造者
3.HouseDircter.java
public class HouseDirector {
HouseBuilder houseBuilder = null;
//1.构造器
public HouseDirector(HouseBuilder housebuilder) {
this.houseBuilder = housebuilder;
}
//2.set
public void setHouseBuilder(HouseBuilder houseBuilder) {
this.houseBuilder = houseBuilder;
}
//如何做交给指挥者
public House constructHouse() {
houseBuilder.buildBasic();
houseBuilder.buildroofed();
houseBuilder.buildWoll();
return houseBuilder.buildHouse();
}
}
一个普通的建造者`
4.CommonHouse.java
public class CommonHouse extends HouseBuilder{
@Override
public void buildBasic() {
// TODO 自动生成的方法存根
System.out.println("打地基");
}
@Override
public void buildWoll() {
// TODO 自动生成的方法存根
System.out.println("砌墙");
}
@Override
public void buildroofed() {
// TODO 自动生成的方法存根
System.out.println("建墙");
}
}
用户
5.client.java
public class Client {
public static void main(String[] args) {
CommonHouse commonHouse = new CommonHouse();
HouseDirector houseDirector = new HouseDirector(commonHouse);
//完成盖房,返回房子
House house = houseDirector.constructHouse();
}
}
运行结果