zoukankan      html  css  js  c++  java
  • JAVA设计模式之建造者模式

    建造者模式:一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

    简单例子:

     1 public class Product 
     2 {
     3     private String partA;
     4     private String partB;
     5     
     6     public void setPartA(String partA) 
     7     {
     8         this.partA = partA;
     9     }
    10 
    11     public void setPartB(String partB)
    12     {
    13         this.partB = partB;
    14     }
    15     
    16     @Override
    17     public String toString()
    18     {
    19         return "[partA = " + partA + ", partB = " + partB + "]";
    20     }
    21 }
    22 
    23 public interface Factory 
    24 {
    25     public void init();
    26     public void buildPartA();
    27     public void buildPartB();
    28     public Product getProduct();
    29 }
    30 
    31 public class Factory1A2B implements Factory
    32 {
    33     private Product product;
    34     
    35     @Override
    36     public void init() 
    37     {
    38         product = new Product();
    39     }
    40     
    41     @Override
    42     public void buildPartA() 
    43     {
    44         product.setPartA("1");
    45     }
    46 
    47     @Override
    48     public void buildPartB() 
    49     {
    50         product.setPartB("2");
    51     }
    52 
    53     @Override
    54     public Product getProduct() 
    55     {
    56         return product;
    57     }
    58 }
    59 
    60 public class Director
    61 {
    62     private Factory factory = new Factory1A2B();
    63     
    64     public Product newProduct()
    65     {
    66         factory.init();
    67         factory.buildPartA();
    68         factory.buildPartB();
    69         return factory.getProduct();
    70     }
    71 }
    72 
    73 public class Test 
    74 {
    75     public static void main(String[] args)
    76     {
    77         Director director = new Director();
    78         System.out.println(director.newProduct());
    79     }
    80 }
  • 相关阅读:
    自主学习1
    动手动脑10.28
    《程序员修炼之道》阅读笔记三
    《程序员修炼之道》阅读笔记
    11月20,21,22训练赛
    Rabbits(跳兔子)
    01背包变式(并查集+dp01背包)
    问题 I: 约会序列(两边枚举)
    问题 J: 直角三角形
    Cow Exhibition (01背包的负数处理)
  • 原文地址:https://www.cnblogs.com/huoxiayu/p/5620451.html
Copyright © 2011-2022 走看看