- 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
- 建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时适用的模式。
-
/** * 产品类,由多个部件组成 */ public class Product { ArrayList list = new ArrayList(); /** * 添加产品的部件 * * @param part */ public void Add(String part) { list.add(part); } public void Show() { System.out.println("\n 产品 创建 ----"); for (Object part : list) {//列举所有的产品部件 System.out.println(part); } } } /** * 抽象建造者,确定产品由两个部件组成,并声明一个得到产品建造后结果的方法 */ public abstract class Builder { public abstract void BuilderPartA(); public abstract void BuilderPartB(); public abstract Product GetResult(); } /** * 具体建造者类 */ public class ConcreteBuilder1 extends Builder { private Product product = new Product(); @Override public void BuilderPartA() { product.Add("部件 A"); } @Override public void BuilderPartB() { product.Add("部件 B"); } @Override public Product GetResult() { return product; } } /** * 具体建造者类 */ public class ConcreteBuilder2 extends Builder { private Product product = new Product(); @Override public void BuilderPartA() { product.Add("部件 X"); } @Override public void BuilderPartB() { product.Add("部件 Y"); } @Override public Product GetResult() { return product; } } /** * 指挥者类 */ public class Director { public void Constructt(Builder builder) { //用来指挥建造过程 builder.BuilderPartA(); builder.BuilderPartB(); } } public class TestUtil { public static void main(String[] args) throws CloneNotSupportedException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Director director = new Director(); Builder builder = new ConcreteBuilder1(); Builder builder1 = new ConcreteBuilder2(); director.Constructt(builder); Product p = builder.GetResult(); p.Show(); director.Constructt(builder1); Product product = builder1.GetResult(); product.Show(); } }
来源:https://www.cnblogs.com/fatRabbit-/p/10201430.html