繁体   English   中英

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

[英]What is the difference between “new A()” and “A.newInstance()”?

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

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

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

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的情况下,提供静态工厂方法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;
}

总体而言,尽管两者之间的差异主要只是设计问题,但这种差异确实非常重要,因为它提供了另一种抽象级别,并使代码更易于理解。

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

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

使用newInstance方法的示例类

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM