在自维护的单例中使用此关键字 class 或始终使用实例

Using this keyword in a self-maintained Singleton class Or use instance always

我正在实现一个自我维护的单例 class,这意味着它有一个私有构造函数和一个 getInstance 方法

public class GPSTracker implements LocationListener {

  private static GPSTracker instance;
  private LocationManager locationManager;
  private field1, field2 ...;

  public static GPSTracker getInstance() {

        if(instance == null)
            instance = new GPSTracker();
        return instance;
    }

  ...
}

问题 1:

因为这个 GPSTracker class 维护它自己的单例对象(称为实例),我在这个 class 中实现的每个方法都应该是 class 字段/成员使用像这样的成员:this.field1 或者总是 instance.field1 ?

问题2:(与1相似)

如您所见,在我上面的示例中,我需要从 LocationListener Override 抽象方法,通常到现在注册到 GPS 就像:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this);

因为我在同一个 class 中实现了覆盖,我是否还需要在这里使用 instance 单例对象(而不是这个)?

如果您能详细说明原因,我将不胜感激?

使用this,这样如果您以后希望它不是单例,那么所有代码​​都不必更改。 getInstance() 方法应该是唯一使用静态 instance 字段的方法。

叫做separation of concerns

getInstance() 方法是唯一关注class.

单例 方面的方法

答案适用于两个问题。

简答:

从技术上讲,这并不重要。使用 this.field1instance.field1(在单例情况下)。

尽管它在两种情况下都可以正常工作并且相同(使用 thisinstance 对象)更推荐使用this关键字

详细答案:

考虑到这一点后,我意识到这并不重要,在这种情况下,单例对象将调用引用 class 成员的方法。
由于单例对象将是调用者 - 使用 this.field1 将引用单例的 field1.

即使 class 正在维护多个对象(来自 class 的同一类型),只要对象调用其成员 this 将始终有效并引用调用者的字段。
这就是 this 关键字的全部技巧!

结论 - 更好的做法是使用 this.field 而不是 instance.field

也给出了一个很好的观点 - 使用 this 所以如果将来你要使 class 非单例,您的代码将准备就绪,您无需将所有 instance.field 更改回 this.field(分离他提到的担忧)。