effective java读书笔记(1)- 静态工厂方法与单例模式

December 10, 2019 · 开发 · 6819次阅读

什么是静态工厂方法

如下不用new来获取实例的方法

    Fragment fragment = MyFragment.newIntance();
    // or 
    Calendar calendar = Calendar.getInstance();
    // or 
    Integer number = Integer.valueOf("3");

优点

  • 静态工厂方法与构造器不同的第一优势在于,它们有名字
  • 第二个优势,不用每次被调用时都创建新对象
  • 第三个优势,可以返回原返回类型的子类
  • 第四个优势,在创建带泛型的实例时,能使代码变得简洁

常见的实际用例场景 - 单例模式:

public class Single1 {
    private static Single1 instance;
    private Single1() {}
    public static Single1 getInstance() {
        if (instance == null) {
            instance = new Single1();
        }
        return instance;
    }
}

标签:java

最后编辑于:2020/05/16 07:55

控制面板