建造者模式在实际工作中常常是在测试类造数据的时候使用,继承既定的Builder类之后,
新的Builder类可以方便的“建造“各种属性。具体见如下代码。
先有默认的既定Builder类:
public interface Builder { public void buildPartA(); public void buildPartB(); public void buildPartC(); }
然后有这个Builder类需要建造的产品类:
public class Product { private String PartA; private String PartB; private String PartC; public void setPartA(String partA) { PartA = partA; } public void setPartB(String partB) { PartB = partB; } public void setPartC(String partC) { PartC = partC; } public String getPartA() { return PartA; } public String getPartB() { return PartB; } public String getPartC() { return PartC; } }
再有这个产品类对应的Builder实现类:
public class ProductBuilder implements Builder{ private Product product ; public ProductBuilder(){ this.product = new Product(); } public void buildPartA() { this.product.setPartA("partA"); } public void buildPartB() { this.product.setPartB("partB"); } public void buildPartC() { this.product.setPartC("partC"); } }
测试类:
public class BuilderTest { public static void main(String[] args) { ProductBuilder productBuilder = new ProductBuilder(); productBuilder.buildPartA(); productBuilder.buildPartB(); productBuilder.buildPartC(); } }
时间: 2024-11-09 14:06:52