建造者模式
Posted 仙人掌的刺
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了建造者模式相关的知识,希望对你有一定的参考价值。
建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及他们的装配方式时适用的模式。
import java.util.LinkedList; import java.util.List; /** * Created by hero on 16-4-3. */ public class Product { private List<String> parts = new LinkedList<>(); public void add(String part) { parts.add(part); } public void show() { for (String p : parts) { System.out.print(p + "\t"); } System.out.println(); } } /** * Created by hero on 16-4-3. */ public abstract class Builder { public abstract void buildPartA(); public abstract void buildPartB(); public abstract Product getResult(); } /** * Created by hero on 16-4-3. */ public class ConcreteBuilder1 extends 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; } } /** * Created by hero on 16-4-3. */ public class ConcreteBuilder2 extends 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; } } /** * Created by hero on 16-4-3. */ public class Director { public void Construct(Builder builder) { builder.buildPartA(); builder.buildPartB(); } } public class Main { public static void main(String[] args) { Director director = new Director(); ConcreteBuilder1 concreteBuilder1 = new ConcreteBuilder1(); ConcreteBuilder2 concreteBuilder2 = new ConcreteBuilder2(); Product product = null; director.Construct(concreteBuilder1); product = concreteBuilder1.getResult(); product.show(); director.Construct(concreteBuilder2); product = concreteBuilder2.getResult(); product.show(); } }
以上是关于建造者模式的主要内容,如果未能解决你的问题,请参考以下文章