建造者模式有四个关键字:产品类、产品接口、建造者、指挥者(房子设计图,房子流程图,工人,包工头)
第一步:产品类(房子设计图)
有产品属性、构造方法、get和set方法
public class Product {
private String one;
private String two;
private String three;
private String four;
public Product() {}
public Product(String one, String two, String three, String four) {
this.one = one;
this.two = two;
this.three = three;
this.four = four;
}
@Override
public String toString() {
return "Builder{" +
"one='" + one + '\'' +
", two='" + two + '\'' +
", three='" + three + '\'' +
", four='" + four + '\'' +
'}';
}
public String getOne() {
return one;
}
public void setOne(String one) {
this.one = one;
System.out.println(one);
}
public String getTwo() {
return two;
}
public void setTwo(String two) {
this.two = two;
System.out.println(two);
}
public String getThree() {
return three;
}
public void setThree(String three) {
this.three = three;
System.out.println(three);
}
public String getFour() {
return four;
}
public void setFour(String four) {
this.four = four;
System.out.println(four);
}
}
第二步:产品接口(造房流程图)
需要抽象方法、返回产品抽象方法(这里抽象方法要返回建造者对象,方便下面指挥者链式调用)
个人理解产品接口是由产品类决定的,其实产品类和产品接口本就是一个东西
public interface BuildTest {
Builder one(); //抽象方法根据产品属性提取的
Builder two();
//这里修改不是void方法,而是要返回一个工人方便指挥者链式调用
Builder three();
Builder four();
Product backProduct(); //这里需要返回产品的方法
}
第三步:建造者类继承产品接口--new出产品对象、具体实现抽象方法、最后返回产品对象
public class Builder implements BuildTest{
Product product=new Product();
//工人需要设计图(产品抽象类),也需要产品类(产品具体类),因为这两个类本质上是一个东西
@Override
public Builder one() {
product.setOne("第一步");
return this;
}
@Override
public Builder two() {
product.setTwo("第二步");
return this;
}
@Override
public Builder three() {
product.setThree("第三步");
return this;
}
@Override
public Builder four() {
product.setFour("第四步");
return this;
}
@Override
public Product backProduct() { //工人将改造好的产品对象返回
return product;
}
}
第四步:指挥者类--创建建造者对象、构建方法、具体工作方法(链式组合工人方法)并返回产品(反回的是工人对象的产品)
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public Product workTest(){
builder.two().three().four().backProduct();
return builder.backProduct();
}
}
第五步:最后调用直接new指挥者,通过改变指挥者去改变产品,而不需要修改建造者的源代码
public static void main(String[] args) {
Director director = new Director(new Builder());
System.out.println(director.workTest());
}