设计模式--建造者模式
建造者模式(builder),将一个复杂对象的构建与他的表示分离,使得同样的构建过程可以创建不同的表示。
1 package com.sun.builder; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 /** 7 * 产品类 由多个部件组成 8 * 9 * @author sunafei 10 * 11 */ 12 public class Product { 13 List<String> parts = new ArrayList<String>(); 14 15 public void add(String part) {//添加产品部件 16 this.parts.add(part); 17 } 18 19 public void show() {//列举所有产品部件 20 System.out.println("产品创建"); 21 for (String part : parts) { 22 System.out.println(part); 23 } 24 } 25 }
1 package com.sun.builder; 2 3 /** 4 * 抽象建造者类,确定产品有两个部件组成,并声明一个得到产品建造后结果的方法getResult 5 * @author SunAFei 6 * 7 */ 8 public abstract class Builder { 9 public abstract void builderPartA(); 10 11 public abstract void builderPartB(); 12 13 public abstract Product getResult(); 14 }
1 package com.sun.builder; 2 3 /** 4 * 具体建造者类 5 * @author SunAFei 6 * 7 */ 8 public class ConcreteBuilder1 extends Builder { 9 10 Product product = new Product(); 11 12 @Override 13 public void builderPartA() { 14 product.add("A"); 15 } 16 17 @Override 18 public void builderPartB() { 19 product.add("B"); 20 } 21 22 @Override 23 public Product getResult() { 24 return product; 25 } 26 27 }
1 package com.sun.builder; 2 3 public class ConcreteBuilder2 extends Builder { 4 5 Product product = new Product(); 6 7 @Override 8 public void builderPartA() { 9 product.add("X"); 10 } 11 12 @Override 13 public void builderPartB() { 14 product.add("Y"); 15 } 16 17 @Override 18 public Product getResult() { 19 return product; 20 } 21 22 }
package com.sun.builder; /** * 指挥者类 * @author SunAFei * */ public class Director { public void construct(Builder builder) {//指挥建造过程 builder.builderPartA(); builder.builderPartB(); } }
1 package com.sun.builder; 2 3 public class BuilderDemo { 4 5 public static void main(String[] args) { 6 Director director = new Director(); 7 Builder b1 = new ConcreteBuilder1(); 8 Builder b2 = new ConcreteBuilder2(); 9 10 director.construct(b1); 11 Product p1 = b1.getResult();//客户不需要知道具体的建造过程 12 p1.show(); 13 14 director.construct(b2); 15 Product p2 = b2.getResult(); 16 p2.show(); 17 } 18 19 }