《Effective Java第二版》阅读小记

  • 方法的签名(signature)由它的名称和所有参数类型组成;签名不包括它的返回类型。
  • 考虑用静态工厂方法代替构造器
    比如EnumSet的静态工厂方法,如果它的元素有64个或者更少,静态工厂方法就会返回一个RegalarEnumSet实例,用单个long进行支持;如果有65个元素或以上,工厂返回JumboEnumSet,用long数组进行支持。
    服务提供者框架:①服务接口;②服务提供者注册API;③服务访问API;④服务提供者接口(可选)
  • 遇到多个构造器参数时要考虑用构建器(Builder模式)
/**
 * @Description:遇到多个构造器参数时要考虑用构建器(Builder模式)
 */
public class NutritionFacts {

    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;

    // 静态内部类
    public static class Builder {
        // 必须的参数使用final修饰,切放在构造器中,为了保证一定要赋值
        // 可选的参数使用默认赋值,使用方法赋值,体现可选性


        // required parameters
        private final int servingSize;
        private final int servings;

        // optional parameters - initialized to default values
        private int calories = 0;
        private int fat = 0;
        private int sodium = 0;
        private int carbohydrate = 0;

        public Builder(int servingSize, int servings) {
            this.servingSize = servingSize;
            this.servings = servings;
        }

        public Builder calories(int val) {
            this.calories = val;
            return this;
        }

        public Builder fat(int val) {
            this.fat = val;
            return this;
        }

        public Builder sodium(int val) {
            this.sodium = val;
            return this;
        }

        public Builder carbohydrate(int val) {
            this.carbohydrate = val;
            return this;
        }

        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }

    // 构造器私有化
    private NutritionFacts(Builder build) {
        this.servingSize = build.servingSize;
        this.servings = build.servings;
        this.calories = build.calories;
        this.fat = build.fat;
        this.sodium = build.sodium;
        this.carbohydrate = build.carbohydrate;
    }

    @Override
    public String toString() {
        return "NutritionFacts{" +
            "servingSize=" + servingSize +
            ", servings=" + servings +
            ", calories=" + calories +
            ", fat=" + fat +
            ", sodium=" + sodium +
            ", carbohydrate=" + carbohydrate +
            '}';
    }

    public static void main(String... args) {
        NutritionFacts nf = new Builder(1, 0).calories(100).fat(50).sodium(22).carbohydrate(250).build();
        System.out.println(nf);
    }
}
  • 用私有构造器或者枚举类型强化Singleton属性
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Description:单例的序列化
 * @Author: baitengpeng
 * @Date: 2018/5/25 下午2:05
 */
public class SingletonSerializable implements Serializable {
    private transient String name = "the singleton object";
    private transient int mumber = 13;

    private static SingletonSerializable singleton = null;

    static{
        singleton = new SingletonSerializable();
    }

    private SingletonSerializable(){
        // 防止通过反射破解单例
        if(null != singleton){
            throw new IllegalStateException("illegal operate");
        }
    }

    // 防止通过序列化反序列化破解单例
    private Object readResolve(){
        return singleton;
    }

    public static SingletonSerializable getInstance(){
        return singleton;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMumber() {
        return mumber;
    }

    public void setMumber(int mumber) {
        this.mumber = mumber;
    }

    @Override
    public String toString() {
        return "SingletonSerializable{" +
            "name='" + name + '\'' +
            ", mumber=" + mumber +
            '}';
    }

    public static void main(String...args)
        throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
        // 写对象
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(SingletonSerializable.getInstance());

        // 读对象
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
        SingletonSerializable singletonSerializable = (SingletonSerializable) ois.readObject();

        // 比较读的对象和原先的对象是否相等
        System.out.println(SingletonSerializable.getInstance() == singletonSerializable);
        System.out.println(SingletonSerializable.getInstance());
        System.out.println(singletonSerializable);

        Class<SingletonSerializable> clazz = SingletonSerializable.class;
        Constructor<?>[] constructors = clazz.getDeclaredConstructors();
        for(Constructor c : constructors){
            c.setAccessible(true);
            System.out.println(SingletonSerializable.getInstance() == c.newInstance());
        }

//        SingletonSerializable objectFromReflection = clazz.newInstance();
//        System.out.println(SingletonSerializable.getInstance() == objectFromReflection);
//        System.out.println(objectFromReflection);
    }
}
  • 通过私有构造器强化不可实例化的能力
/**
 * @Description:工具类,只包含静态方法和静态成员变量,这种类不希望被实例化
 * @Author: baitengpeng
 * @Date: 2018/5/25 下午3:11
 */
public class UtilityClass {
    // 将它的构造器声明为private,且为了防止反射,在构造器中抛出异常
    private UtilityClass(){
        throw new AssertionError();
    }
    // 静态方法和静态成员变量
    // ...
}
  • 避免创建不必要的对象
    当你应该重用现有对象的时候,请不要创建新的对象。

  • 消除过期的对象引用
    对于不再使用的对象引用,将其赋值为null。
    巧妙使用WeakHashMap

  • 避免使用终结方法
    从一个对象变得不可到达开始,到它的终结方法被执行,所花费的这段时间是任意长的。终结方法不能保证会被及时地执行。
    如果未被捕获的异常在终结过程中被抛出来,那么方法会终止,而且什么都不会打印出来。
    如果需要终止,可以为对象提供一个显式的终止方法。多和try{}catch(){}finally{}结合起来使用。比如InputStream的close方法。

  • 覆盖equals时请遵守通用约定
    如果类具有自己特有的“逻辑相等”概念,则需要覆盖equals方法。
    比较float和double类型的值使用Float.compareDouble.compare
    为了提高equals方法的性能,应该先比较最有可能不一致的域,或者是开销最低的域。
    equals满足:①自反性②对称性③传递性④非空性

  • 覆盖equals时总要覆盖hashCode
    equals相等,hashCode必相等。
    equals不等,hashCode有可能相等。
    equals不等的对象,hashCode相等,如果是在HashMap中,就是放在一个桶里,两个对象链接起来,所以hashCode不相等可以提高性能。
    重写hashCode方法
数字31的一个优良的性质是:乘法可以被位移和减法替代: 
31 * i == (i << 5) - i
  • 始终要覆盖toString
    可以通过toString获取到关键性的信息,而且可读性好。

  • 谨慎地覆盖clone

猜你喜欢

转载自blog.csdn.net/a_842297171/article/details/80440932