Builder设计模式:个人认为,核心在于两个类。Builder类和Director类。通过Builder类和Director类,把万事万物抽象为部件和组装两部分。通过两部分的配合,把最终的产品,展示给客户。上图,只组装了一款产品。
公司做大以后,不仅可以提供一款产品。根据已有的功能多少和精简,可以快速生产出多种的产品,只要不同的construct和Product就可以了。construct提供了三个功能,说明这是一款lenovo的thinkpadT430笔记本电脑。如果construct只提供了一个show功能,那可能就是联想的平板了。
public interface Builder { void call(); void show(); void work(); Product getResult(); }
public class Lenovo implements Builder { private Product lenovo; public void call() { // TODO: implement lenovo.setCallFun("lenovo call"); } public void show() { // TODO: implement lenovo.setShowFun("lenovo show"); } public void work() { // TODO: implement lenovo.setWorkFun("lenovo work"); } public Product getResult() { // TODO: implement return this.lenovo; } public Lenovo() { // TODO: implement lenovo = new Product(); } }
public class Product { private String callFun; private String showFun; private String workFun; public String getCallFun() { return callFun; } public void setCallFun(String newCallFun) { callFun = newCallFun; } public String getShowFun() { return showFun; } public void setShowFun(String newShowFun) { showFun = newShowFun; } public String getWorkFun() { return workFun; } public void setWorkFun(String newWorkFun) { workFun = newWorkFun; } }
public class Director { private Builder builder; public Director(Builder builder) { // TODO: implement this.builder= builder; } public void construct() { // TODO: implement builder.call(); builder.show(); builder.work(); } }
public class CallBuilder { private static Builder builder; private static Director director; private static Product product; public static void main(String[] args) { builder = new Lenovo(); director = new Director(builder); director.construct(); product = builder.getResult(); System.out.println(product.getCallFun()); System.out.println(product.getShowFun()); System.out.println(product.getWorkFun()); } }
原文地址:http://lylovewyf.blog.51cto.com/1288567/1440952