美文网首页
读书笔记:《Effective Java中文版第二版》

读书笔记:《Effective Java中文版第二版》

作者: Pale_Eyes | 来源:发表于2017-12-11 14:04 被阅读0次

    1.创建和销毁对象

    • 第一条:考虑用静态工厂方法替代构造器
    public static Boolean valueOf(boolean b){
      return b ? Boolean.TRUE : Boolean.FALSE;
    }
    
    • 第二条:遇到多个构造器参数时要考虑用构建器
    //重叠构造器模式
    public class Demo {
      private final int a;
      private final int b;
      private final int c;
      public Demo(int a){
        this(a,0);
      }
      public Demo(int a,int b){
        this(a,b,0);
      }
      public Demo(int a,int b,int c){
        this.a = a;
        this.b = b;
        this.c = c;
      }
    }
    
    //JavaBean模式
    public class Demo {
        private int a = -1;
        private int b = 0;
        private int c = 0;
        public Demo() {
        }
        public void setA(int a) {
            this.a = a;
        }
        public void setB(int b) {
            this.b = b;
        }
        public void setC(int c) {
            this.c = c;
        }
    }
    
    //Builder模式
    public class Demo {
        private final int a;
        private final int b;
        private final int c;
        public static class Builder{
            private final int a;
            private int b = 0;
            private int c = 0;
            public Builder(int a){
                this.a = a;
            }
            public Builder b(int val){
                b = val;
                return this;
            }
            public Builder c(int val){
                c = val;
                return this;
            }
            public Demo build(){
                return new Demo(this);
            }
        }
        private Demo(Builder builder){
            a = builder.a;
            b = builder.b;
            c = builder.c;
        }
    }
    

    这里a是必填参数无默认值,b是非必填参数有默认值

        public static void main(String[] args) {
            Demo demo1 = new Builder(250).b(12).c(36).build();
            Demo demo2 = new Builder(250).c(36).build();
        }
    

    相关文章

      网友评论

          本文标题:读书笔记:《Effective Java中文版第二版》

          本文链接:https://www.haomeiwen.com/subject/qlyiixtx.html