zoukankan      html  css  js  c++  java
  • Builder 设计模式

    public class xxxConfig{
      //需要设置的字段
       private String mName;
       private String mPossword;    
      public static class Build{
         //需要设置的字段
           private String mName;
           private String mPossword;
        private xxxConfig(){}

        private Build setName(String name){
          mName = name;
          return this;
        }  
        public Build setPossword(String password){
          mPassword = password;
          return this;
        } 
        public void applyConfig(xxxConfig config){
          config.mName = this.mName;
          config.mPassword = this.mPassword;
        }

        public xxxConfig create(){
          xxxConfig config = new xxxConfig();
          applyConfig(config);
          return config;
        }
      }
    }

      

    class xxx{
        private xxxConfig mConfig;
       public void init(xxxConfig config){
         mConfig = config;
        //检测config的合法性,做一些初始化操作
        checkConfig();
       }

       private void checkConfig(){
        if(mConfig.mName != null){
          //使用name的具体操作
        }
       }
    }


    调用:
      xxxConfig config = xxxConfig.Build.setName("tom").setPassword("123").create();
      new xxx().init(config);

      

     使用场景:

      1、需要生成的产品对象有复杂的内部结构。
      2、需要生成的产品对象的属性相互依赖,建造者模式可以强迫生成顺序。
      3、在对象创建过程中会使用到系统中的一些其它对象,这些对象在产品对象的创建过程中不易得到。

    优点:

      1.良好的封装性,可以使客户端不必知道产品内部组成的细节。

      2.独立,容易扩展

    缺点:

      产生多余的Builder对象以及Director对象,消耗内存。

  • 相关阅读:
    第三章:Hadoop简介及配置Hadoop-1.2.1,hbase-0.94.13集群
    maven环境的搭建,lemon-OA办公系统的搭建
    如何打开mo文件并修改 PoEdit
    安装Elastix-2.4版本
    RabbitMQ安装
    Yum编译安装Error Downloading Packages报错
    linux:ping不通www.baidu.com
    tar命令解压缩出错
    PV、UV
    使用存储过程创建数据
  • 原文地址:https://www.cnblogs.com/IT-lss/p/9684968.html
Copyright © 2011-2022 走看看