【问题标题】:What is the difference between "new A()" and "A.newInstance()"?“new A()”和“A.newInstance()”有什么区别?
【发布时间】:2012-01-17 03:14:05
【问题描述】:

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

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

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

【问题讨论】:

  • 通常,A.newInstance 用于单例设计模式。

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


【解决方案1】:

newInstance() 通常用作实例化对象的一种方式,而无需直接调用对象的默认构造函数。例如,它经常用于实现单例设计模式:

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 属性)。

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;
}

总体而言,虽然两者之间的区别主要只是设计问题,但这种区别确实很重要,因为它提供了另一个抽象级别,并使代码更容易理解。

【讨论】:

  • 嗯,但你不能在构造函数中包装相同的代码吗? public class MyFragment { MyFragment(Bundle args) { this.setArguments(args) ... } MyFragment(int index) { Bundle args = new Bundle(); args.putInt(...); this(args) }
  • 你试图改变最终变量“instance”的引用,它的错误,不是吗?
【解决方案2】:

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

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

Sample class with newInstance method

【讨论】:

    【解决方案3】:

    new()是创建对象的关键字,知道类名就可以使用
    new instance ()是创建对象的方法,不知道类名就可以使用关于类名

    【讨论】:

      猜你喜欢
      • 2012-11-23
      • 2014-04-12
      • 2018-08-02
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 2018-06-04
      相关资源
      最近更新 更多