23种设计模式之建造者模式
Posted java_pro
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了23种设计模式之建造者模式相关的知识,希望对你有一定的参考价值。
建造者模式(Builder):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
package designMode.builder; import java.util.LinkedList; import java.util.List; class Product { List<String> parts = new LinkedList<String>(); public void add(String part){ parts.add(part); } public void show(){ System.out.println("产品创建..."); for (String str : parts) { System.out.println(str); } } }
package designMode.builder; interface Builder { void buildPartA(); void buildPartB(); Product getResult(); }
package designMode.builder; class ConcreteBuilder1 implements Builder{ private Product product = new Product(); @Override public void buildPartA() { product.add("部件A"); } @Override public void buildPartB() { product.add("部件B"); } @Override public Product getResult() { return product; } } class ConcreteBuilder2 implements Builder{ private Product product = new Product(); @Override public void buildPartA() { product.add("部件X"); } @Override public void buildPartB() { product.add("部件Y"); } @Override public Product getResult() { return product; } }
package designMode.builder; class Director { public void construct(Builder builder){ builder.buildPartA(); builder.buildPartB(); } }
package designMode.builder; class Test { public static void main(String[] args) { Director director = new Director(); Builder b1 = new ConcreteBuilder1(); Builder b2 = new ConcreteBuilder2(); director.construct(b1); Product p1 = b1.getResult(); p1.show(); director.construct(b2); Product p2 = b2.getResult(); p2.show(); } }
以上是关于23种设计模式之建造者模式的主要内容,如果未能解决你的问题,请参考以下文章