"new A()"和"A.newInstance()"之间有什么区别?

rex*_*rex 13 java singleton android design-patterns android-fragments

我什么时候应该更喜欢一个?下面显示的方法的目的是什么?

class A {
    public static A newInstance() {
        A a = new A();
        return a ;
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释这两个电话之间的区别吗?

Ale*_*ood 16

newInstance()通常用作实例化对象而不直接调用对象的默认构造函数的方法.例如,它通常用于实现Singleton设计模式:

public class Singleton {
    private static final Singleton instance = null;

    // make the class private to prevent direct instantiation.
    // this forces clients to call newInstance(), which will
    // ensure the class' Singleton property.
    private Singleton() { } 

    public static Singleton newInstance() {
        // if instance is null, then instantiate the object by calling
        // the default constructor (this is ok since we are calling it from 
        // within the class)
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,程序员强制客户端调用newInstance()以检索该类的实例.这很重要,因为简单地提供默认构造函数将允许客户端访问类的多个实例(这违反了Singleton属性).

Fragments 的情况下,提供静态工厂方法newInstance()是很好的做法,因为我们经常希望将初始化参数添加到新实例化的对象.我们可以提供一种newInstance()为它们执行此操作的方法,而不是让客户端调用默认构造函数并手动设置片段参数.例如,

public static MyFragment newInstance(int index) {
    MyFragment f = new MyFragment();
    Bundle args = new Bundle();
    args.putInt("index", index);
    f.setArguments(args);
    return f;
}
Run Code Online (Sandbox Code Playgroud)

总的来说,虽然两者之间的差异主要只是设计问题,但这种差异非常重要,因为它提供了另一层次的抽象,使代码更容易理解.