EffectiveJava之创建和销毁对象篇

412次阅读  |  发布于1年以前

小伙伴们好呀, 今天来和大家分享下 《Effective Java》这本书的 第2章 —— 创建和销毁对象

一共有 9 点,一起看看叭~

1. 考虑用 静态工厂方法 而不是构造器

有这五个优点:

  1. 有方法名
  2. 不用每次都创建对象
  3. 可以返回任意子类
  4. 可以根据不同的入参而返回不同的类
  5. 在编写包含方法的类时,返回对象的类不需要存在

A. 有方法名

这个优点确实很显眼 ,毕竟构造器名固定了

B. 不用每次都创建对象

这个也好理解,可以缓存对象, 设计思想上可参考 亨元设计模式

例如 valueOf 方法

BigInteger

Boolean

C. 可以返回任意子类

这个作者举了 Collections 这个工具类,但是我也没啥特别的感觉,感觉和 面向接口编程 差不多的意思

D 可以根据不同的入参而返回不同的类

这个可以参考 Spring 中 BeanFactory 接口的 getBean 方法。

这个我便轻车熟路了,它可以对业务模块进行解耦,方便扩展

接口A a = applicationContext.getBean(参数);
a.common();

E. 在编写包含方法的类时,返回对象的类不需要存在

这个还是 面向接口编程 好吧……

作者举了 JDBC 这个例子。

Connection conn=DriverManager.getConnection(xxx)

2. 如果构造器有很多参数,建议用 builder 去创建对象

这个就是 建设者模式 的使用了,下面是作者 Joshua Bloch 在 GitHub 仓库给的例子

package effectivejava.chapter2.item2.builder;

// Builder Pattern  (Page 13)
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 {
        // 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)
        { calories = val;      return this; }
        public Builder fat(int val)
        { fat = val;           return this; }
        public Builder sodium(int val)
        { sodium = val;        return this; }
        public Builder carbohydrate(int val)
        { carbohydrate = val;  return this; }

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

    private NutritionFacts(Builder builder) {
        servingSize  = builder.servingSize;
        servings     = builder.servings;
        calories     = builder.calories;
        fat          = builder.fat;
        sodium       = builder.sodium;
        carbohydrate = builder.carbohydrate;
    }

    public static void main(String[] args) {
        NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8)
                .calories(100).sodium(35).carbohydrate(27).build();
    }
}

看到这个 链式调用,不得不感叹下 stream 源码,封装的超级牛,要 List,要 Map 等都可以很随意的转换出来!

Builder 设计模式步骤解析

3. 用 枚举或者私有构造器 来强化 单例属性

这个就差不多在说 单例模式

可以看看之前的文章:

[一文带你看遍单例模式的八个例子,面试再也不怕被问了] (我都忘光了)

这两个也是作者 Joshua Bloch 在 GitHub 仓库给的例子

枚举

package effectivejava.chapter2.item3.enumtype;

// Enum singleton - the preferred approach (Page 18)
public enum Elvis {
    INSTANCE;

    public void leaveTheBuilding() {
        System.out.println("Whoa baby, I'm outta here!");
    }

    // This code would normally appear outside the class!
    public static void main(String[] args) {
        Elvis elvis = Elvis.INSTANCE;
        elvis.leaveTheBuilding();
    }
}

属性

package effectivejava.chapter2.item3.field;

// Singleton with public final field  (Page 17)
public class Elvis {
    public static final Elvis INSTANCE = new Elvis();

    private Elvis() { }

    public void leaveTheBuilding() {
        System.out.println("Whoa baby, I'm outta here!");
    }

    // This code would normally appear outside the class!
    public static void main(String[] args) {
        Elvis elvis = Elvis.INSTANCE;
        elvis.leaveTheBuilding();
    }
}

4. 用 私有构造器 来限制实例化

这个也是 单例模式 的影子了。

5. 通过 依赖注入 而不是 硬编码 的方式使用资源

这句话听着还有点别扭,作者举了一个例子,就是一个工具里把 字典 写死了,这样是不对的,应该是下面这种依赖注入的写法才对。

个人感觉。。。还是 面向接口编程

// Dependency injection provides flexibility and testability
public class SpellChecker {
 private final Lexicon dictionary;

    public SpellChecker(Lexicon dictionary) {
     this.dictionary = Objects.requireNonNull(dictionary);
    }

    public boolean isValid(String word) { ... }
    public List<String> suggestions(String typo) { ... }
}

6. 避免创建不必要的对象

比如,String 对象的创建

// 这样写每次都创建新对象,不要使用
String s= new String("Java4ye");

// 使用
String s= "Java4ye";

开头提到的 亨元模式valueOf 等缓存对象的方法。

日常中各种连接的建立,线程池的使用等等。

注意 基本数据类型和包装类型


// Hideously slow! Can you spot the object creation?
private static long sum() {
    Long sum = 0L;
    for (long i = 0; i <= Integer.MAX_VALUE; i++)
    sum += i;
    return sum;
}

将 Long 改成 long

这里试了下,确实很夸张,从 7s 到 1s,所以在 计算时,一定要留意用 基本数据类型去计算,小心自动装箱拆箱。

7. 清除过时对象的引用

这个就是大名鼎鼎的 内存泄漏

经常看到很多 线上环境cpu飙升内存溢出 宕机之类的问题,基本都是这个数据结构使用不当造成的。

比如 ThreadLocal , 还有 集合中存着对象的引用 没有被清掉等问题

你能从这个例子中找到问题吗

package effectivejava.chapter2.item7;
import java.util.*;

// Can you spot the "memory leak"?  (Pages 26-27)
public class Stack {
    private Object[] elements;
    private int size = 0;
    private static final int DEFAULT_INITIAL_CAPACITY = 16;

    public Stack() {
        elements = new Object[DEFAULT_INITIAL_CAPACITY];
    }

    public void push(Object e) {
        ensureCapacity();
        elements[size++] = e;
    }

    public Object pop() {
        if (size == 0)
            throw new EmptyStackException();
        return elements[--size];
    }

    /**
     * Ensure space for at least one more element, roughly
     * doubling the capacity each time the array needs to grow.
     */
    private void ensureCapacity() {
        if (elements.length == size)
            elements = Arrays.copyOf(elements, 2 * size + 1);
    }

//    // Corrected version of pop method (Page 27)
//    public Object pop() {
//        if (size == 0)
//            throw new EmptyStackException();
//        Object result = elements[--size];
//        elements[size] = null; // Eliminate obsolete reference
//        return result;
//    }

    public static void main(String[] args) {
        Stack stack = new Stack();
        for (String arg : args)
            stack.push(arg);

        while (true)
            System.err.println(stack.pop());
    }
}

说到底还是 对象引用 的问题,可以看看 4ye 之前写的

[四种引用类型在Springboot中的使用] ,看看 Springboot 和线程池是如何巧妙用上 软引用和弱引用 的。

8. 避免 finalize 方法和 Cleaner 类的使用

这两个都没用过,而且 finalize 方法不是你调用就立刻执行的。

Cleaner 也是第一次见,继承了 虚引用

溜溜溜~

9. 用 try-with-resources 而不是 try-finally

这里作者主要说这个 twr 比较优雅,以及解决了异常覆盖的问题。

这个我之前写过的这篇文章也有提到过

[try-with-resources 这样坑过我]

总之,就是要注意 关闭这个流,会不会有其他影响,有的话还是手动关闭好了。

特别是 Web 端,不要把客户端请求吃掉了,还没返回信息过去。

总结

看完之后,最大的收获是

  1. 对创建出来的对象要考虑复用,即缓存的使用,会涉及到亨元,单例设计模式的使用
  2. 面向接口编程,多考虑 依赖注入 而不是硬编码
  3. 构造器参数过多时要用 Builder 模式
  4. 注意 自动装箱拆箱 带来的开销,如上面的 Long 计算
  5. 注意内存泄漏,如 ThreadLocal , 其他集合,缓存等,注意对象引用的处理,软引用和弱引用的巧妙使用,可以提升 JVM 的 GC 效率。
  6. 注意 TWR 自动关闭资源 带来的隐患,结合业务。

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8