effective JAVA 阅读笔记。

第一条:考虑用静态工厂方法来代替构造器。

优势:

1,他们有重命名,这回让我们的行为更加清晰,增加可读性。

2,不必每次都创建一个对象,减少对象的创建与销毁,提高性能。

3,可返回类型的各种子类型,多态优势。

4,对于复杂对象的创建更加简洁。

缺陷:

1,他们容易与其他静态方法混淆。建议常规命名,或者创建工厂类进行专门管理。

 

 

第二条遇到多个构造器参数时使用构建器

通过构建器管理参数,这样就无需多个不同参数类型的构造器了。

优势:

1,对于大型类不用创建多个奇怪参数有序的构造器.

2、易于配置参数无需多条javabean的Set方法导致对象在不同时间段不一致.

3、易于对参数管理阅读。

缺陷:

多创建了一个构造器,导致性能损失。

示例:

package com.dhh.all;

public class Nf {
    private final int a;
    private final int b;
    private final int c;
    private final int d;
    private final int e;
    public static class Buileer{
        private int a=0;
        private int b=0;
        private int c=0;
        private int d=0;
        private int e=0;
        
        
        public Buileer(int a, int b) {
            super();
            this.a = a;
            this.b = b;
        }
        public Buileer setC(int c) {
            this.c = c;
            return this;
        }
        public Buileer setD(int d) {
            this.d = d;
            return this;
        }    
        public Buileer setE(int e) {
            this.e = e;
            return this;
        }
        
        public Nf builder(){
            return new Nf(this);
        }
        
    }
    
    
    private Nf(Buileer b){
        this.a=b.a;
        this.b=b.b;
        this.c=b.c;
        this.d=b.d;
        this.e=b.e;
    }

    public static void main(String[] args) {
        Nf n=new Nf.Buileer(1,2).setC(1).setD(2).setE(3).builder();
    }
}

 

posted @ 2018-04-11 23:58  酒皇  阅读(103)  评论(0编辑  收藏  举报