建造模式【java版】
应用场景:
将构建一个复杂产品的过程进行分解:
1)每个部件的创建:专注于每个部件自身的创建
2)整体产品的创建:将创建好的各个部件传递给产品类
一个复杂的产品对象由若干个部件对象装配而成,由此可使整个复杂构建过程的逻辑更加清晰,可读性更强
一、组成结构
组成:
抽象建造者
具体建造者
指挥者
产品类
产品类:
public class HouseProduct {
private int area;
private int roomCount;
private String color;
public HouseProduct(int area,int roomCount,String color) {
this.area=area;
this.roomCount=roomCount;
this.color=color;
}
public void printHouseInfo(){
System.out.println("房屋信息已获取。面积:"+this.area+"平米,房间数: "
+this.roomCount+"个,主色调:"+this.color);
}
}
抽象建造者:
public interface Builder {
public void buildFundation();//建造地基
public void buildFrame();//建造主体结构
public void buildDecoration();//装修
public HouseProduct getHouseProduct();//返回组装好的产品对象
}
具体建造者类:
public class ConcreteBuilder implements Builder {
private int area;
private int roomCount;
private String color;
public ConcreteBuilder(int area,int roomCount,String color) {
this.area=area;
this.roomCount=roomCount;
this.color=color;
}
public void buildFundation() {
System.out.println("开始建造地基,总面积为:"+this.area+"平方米");
}
public void buildFrame() {
System.out.println("开始建造主体结构,房间数为:"+this.roomCount+"个");
}
public void buildDecoration() {
System.out.println("开始进行装修,主色调为:"+this.color);
}
public HouseProduct getHouseProduct() {
System.out.println("将所有部件传递给产品类,产品类完成所有部件的装配...");
HouseProduct theHouseProduct = new HouseProduct (this.area,this.roomCount,this.color);
System.out.println("所有部件装配完成,可返回完整的产品对象!");
return theHouseProduct;
}
}
指挥者类:
public class Director {
//“指挥者”指定各个部件的建造顺序,通过调用“具体建造者”的方法来完成
public void construnct(Builder builder){
builder.buildFundation();
builder.buildFrame();
builder.buildDecoration();
}
}
二、测试
测试代码:
public class Main {
public static void main(String[] args) {
System.out.println("开始测试建造模式。。。");
System.out.println();
Builder builder=new ConcreteBuilder(800,7,new String("红色"));//创建一个“具体建造者”
Director director=new Director();//创建一个“指挥者”
director.construnct(builder);//“指挥者”指挥“具体建造者”完成整个房屋的创建
HouseProduct houseProduct=builder.getHouseProduct();//“具体建造者”把刚创建的房屋对象返回回来
System.out.println();
houseProduct.printHouseInfo();//输出新创建的房屋信息
}
}
运行结果: