我应该什么时候比另一个更喜欢?下面显示的方法的目的是什么?“new A()”和“A.newInstance()”有什么区别?
class A {
public static A newInstance() {
A a = new A();
return a ;
}
}
有人可以向我解释这两个电话之间的区别吗?
我应该什么时候比另一个更喜欢?下面显示的方法的目的是什么?“new A()”和“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方法执行初始化并返回给您会更有意义一个准备好使用的对象。
例如,Activity
s和Fragment
s未在其构造函数中初始化。相反,它们通常在onCreate中初始化。因此,newInstance方法通常接受对象在初始化期间需要使用的任何参数,并将它们存储在该对象稍后可以读取的Bundle中。这样的例子可以看这里:
new()
是用于创建对象的关键字,而我们知道类名
new instance()
它可以用来是用于创建对象的方法,它可以用来当我们不知道的类名都
通常,A.newInstance用于单身设计模式。 – 2012-01-17 03:34:25