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

时间:2012-01-17 03:14:06

标签: java android design-patterns singleton android-fragments

我应该何时优先选择其中一个?下面显示的方法的目的是什么?

class A {
    public static A newInstance() {
        A a = new A();
        return a ;
    }
}

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

3 个答案:

答案 0 :(得分: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;
    }
}

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

对于Fragment s,提供静态工厂方法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;
}

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

答案 1 :(得分:1)

在你的例子中,它们是等价的,并没有真正的理由选择一个而不是另一个。但是,如果在回送类的实例之前执行某些初始化,则通常使用newInstance。如果每次通过调用其构造函数请求新的类实例时,最终都会在使用该对象之前设置一堆实例变量,那么让newInstance方法执行该初始化并返回给您更有意义一个准备好使用的对象。

例如,ActivityFragment未在其构造函数中初始化。相反,它们通常在onCreate期间初始化。因此,通常的做法是newInstance方法接受对象在初始化期间需要使用的任何参数,并将它们存储在对象可以从以后读取的Bundle中。这方面的一个例子可以在这里看到:

Sample class with newInstance method

答案 2 :(得分:0)

new()是用于创建对象的关键字,可以在我们知道类名称时使用它          new instance ()是一种用于创建对象的方法,当我们不知道类名时可以使用它

相关问题