zoukankan      html  css  js  c++  java
  • 构建器模式

    构建器模式

    // 定义
    public class User {
        private final Integer id;
        private final String name;
        private Integer age;
        private String sex;
        private String phone;
    
        private User(UserBuilder builder){
            this.id=builder.id;
            this.name=builder.name;
            this.age=builder.age;
            this.sex=builder.sex;
            this.phone=builder.phone;
        }
    
        public static class UserBuilder{
            private final Integer id;
            private final String name;
            private Integer age;
            private String sex;
            private String phone;
    
    
            public UserBuilder(Integer id,String name){
                this.id=id;
                this.name=name;
            }
    
            public UserBuilder age(Integer age){
                this.age=age;
                return this;
            }
    
            public UserBuilder sex(String sex){
                this.sex=sex;
                return this;
            }
    
            public UserBuilder phone(String phone){
                this.phone=phone;
                return this;
            }
    
            public User build(){
                return new User(this);
            }
        }
    }
    
    // 使用
    User.UserBuilder builder=new User.UserBuilder(222,"bbb");
    User user=builder.phone("aaa").age(333).sex("cccc").build();
    
    • 构建器模式优点
      • 为了解决安全性问题,使用final限制属性不可变并移除setter方法等;
      • 为了解决可读性和扩展性问题,通过使用静态嵌套类,在其中设置可变参数方法等;
      • 相对于传统的setter/getter方法,
        • 传统的方式成员变量不可以是 final 类型,失去了不可变对象的很多好处;。
        • 对象状态不连续:你必须调用7次setter方法才能得到一个具备7个属性值得变量,在这期间用户可能拿到不完整状态的对象。如果有N个属性,岂不是要person.setXXX调用N次?此种方式不优雅。
  • 相关阅读:
    2018年6月2号(线段树(2))
    [朋友(dalao)们的友链](¦3[▓▓]让我安详的躺一会儿...
    Hello,World
    算法笔记:数论基础
    [单源最短路]逃离僵尸岛
    算法笔记:最小生成树
    算法笔记:单调队列
    算法笔记:高斯消元
    [博客..配置?]博客园美化
    [大模拟]LuoGu P2033 Chessboard Dance
  • 原文地址:https://www.cnblogs.com/frankltf/p/10299807.html
Copyright © 2011-2022 走看看