建造者模式是将一个产品的属性与其制造的过程分开,因为不同产品的制造过程可能不一样,需要定制化。
具体代码呢,以建造房子为例子,见如下:
1、明确需要的产品:
// 我们只对产品进行属性定义 不做行为定义
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;
}
}
2、抽象制造该产品的类:
//抽象具体产品的构建过程
public abstract class HouseBuilder {
protected House house = new House();
public abstract void buildBasic();
public abstract void buildWall();
public abstract void buildRoof();
public House buildHouse(){
return house;
}
}
3、指挥者聚合建造者:
public class HouseDirector {
//聚合抽象的建造者
HouseBuilder houseBuilder = null;
//通过构造器传入
public HouseDirector(HouseBuilder houseBuilder) {
this.houseBuilder = houseBuilder;
}
public House constructHouse(){
houseBuilder.buildBasic();
houseBuilder.buildRoof();
houseBuilder.buildWall();
return houseBuilder.buildHouse();
}
}
4、不同类型的房子:
//普通房子的要求
public class CoommonHouse extends HouseBuilder{
@Override
public void buildBasic() {
System.out.println("普通房地基5米");
}
@Override
public void buildWall() {
System.out.println("普通房砌墙0.5米");
}
@Override
public void buildRoof() {
System.out.println("普通房盖顶");
}
}
//高楼的标准
public class HighHouse extends HouseBuilder{
@Override
public void buildBasic() {
System.out.println("高楼地基");
}
@Override
public void buildWall() {
System.out.println("高楼砌墙");
}
@Override
public void buildRoof() {
System.out.println("高楼盖顶");
}
}
测试如下:
public class HouseTest {
public static void main(String[] args) {
House h1 = new HouseDirector(new CoommonHouse()).constructHouse();
House h2 = new HouseDirector(new HighHouse()).constructHouse();
}
}
结果如下:
普通房地基5米
普通房盖顶
普通房砌墙0.5米
高楼地基
高楼盖顶
高楼砌墙