标签:
建造者模式是对象的创建模式,可以将一个产品的内部表现与产品的生产过程分隔开,从而可以使一个建造过程生成具有不同内部表象的产品。
1 //产品类 2 class Product{ 3 //产品的内部表象 4 private String part1; 5 private String part2; 6 public String getPart1() { 7 return part1; 8 } 9 public void setPart1(String part1) { 10 this.part1 = part1; 11 } 12 public String getPart2() { 13 return part2; 14 } 15 public void setPart2(String part2) { 16 this.part2 = part2; 17 } 18 } 19 20 //抽象建造者接口 21 interface Builder{ 22 public void buildPart1(); 23 public void buildPart2(); 24 public Product getProduct(); 25 } 26 27 //具体建造者类 28 class ConcreteBuilder implements Builder{ 29 30 //持有产品实例 31 private Product product = new Product(); 32 33 //构建产品第一部分 34 @Override 35 public void buildPart1() { 36 product.setPart1(""); 37 } 38 39 //构建产品第二部分 40 @Override 41 public void buildPart2() { 42 product.setPart2(""); 43 } 44 45 //获得产品 46 @Override 47 public Product getProduct() { 48 return product; 49 } 50 51 } 52 53 //导演者类 54 class Director{ 55 private Builder builder; 56 57 public Director(Builder builder){ 58 this.builder = builder; 59 } 60 61 //产品的构建 62 public void construct(){ 63 builder.buildPart1(); 64 builder.buildPart2(); 65 } 66 } 67 68 public class MyTest { 69 70 /** 71 * @param args 72 */ 73 public static void main(String[] args) { 74 Builder builder = new ConcreteBuilder(); 75 Director director = new Director(builder); 76 director.construct(); 77 Product product = builder.getProduct(); 78 } 79 80 }
标签:
原文地址:http://www.cnblogs.com/gsbm/p/4770000.html