1.Product产品类,目前有两种产品A,B
2.他们的构造者是ProductABuilder和ProductBBuilder。
测试类:
package com.nstc.builder;
public class Test {
public static void main(String[] args) {
ProductBuilderDirector productBD1 = new ProductBuilderDirector(new ProductABuilder());
Product a = productBD1.build();
ProductBuilderDirector productBD2= new ProductBuilderDirector(new ProductBBuilder());
Product b = productBD2.build();
System.out.println(a);
System.out.println(b);
}
}
构造者接口(抽象)
package com.nstc.builder;
public abstract class AProductBuilder {
protected abstract void buildName();
protected abstract void buildPrice();
protected abstract Product getProduct();
}
产品A的构造者:
package com.nstc.builder;
public class ProductABuilder extends AProductBuilder {
private Product product = new Product();@Override
protected void buildName() {
this.product.setName("产品A的名称");
}@Override
protected void buildPrice() {
this.product.setPrice(20);
}@Override
protected Product getProduct() {
return this.product;
}}
产品B的构造者:
package com.nstc.builder;
public class ProductBBuilder extends AProductBuilder {
private Product product = new Product();@Override
protected void buildName() {
this.product.setName("产品B的名称");
}@Override
protected void buildPrice() {
this.product.setPrice(30);
}@Override
protected Product getProduct() {
return this.product;
}}
构造者的指导者:
package com.nstc.builder;
public class ProductBuilderDirector {
private AProductBuilder builder = null;
public ProductBuilderDirector(AProductBuilder builder) {
this.builder = builder;
}
public Product build() {
builder.buildName();
builder.buildPrice();
return builder.getProduct();
}
}
产品类:
package com.nstc.builder;
public class Product {
private String name;
private Integer price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Product [name=" + name + ", price=" + price + "]";
}
}