本文介绍了正确实现按需初始化持有者习语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个版本的按需持续保持成语:




上面的主要区别是第一个声明 INSTANCE private ,但第二个已将 INSTANCE 声明为公开



请告诉我应该使用哪个。 / p>




对不起,我没有发现使用私人 strong>在我的应用程序:

  public class Singleton {
private int x;
public int getX(){
return x;
}

private Singleton(){}

私人静态类LazyHolder {
//私人和公共作品
私人静态Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance(){
return LazyHolder.INSTANCE;
}
}

我所做的只是调用 Singleton.getInsance()。getX(),所以这两个版本都工作。
因此我想知道使用它们的情况。

解决方案

有几个事情要解释单例和按需初始化持有者习语。我们去:



1)访问修饰符:



通常你不能访问字段和方法如果他们是私人的另一个类。如果访问类在同一个包中,它们必须至少是包私有(没有修饰符)。所以正确的实现方法是:

  public class Singleton {
...
private static class LazyHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return LazyHolder.INSTANCE;
}
}

但是,说明:

That means, declaring the field INSTANCE as private still allows the access from inside the top level class Singleton. But the compiler must do some tricks to get around the private modifier: It inserts package private methods for getting and setting such a field.

In fact, it does not matter, which modifier you place on it. If it is public, it still cannot be accessed from other classes than Singleton. However ... I think the package private access is the best. Making it public does not makes sense. Making it private forces the compiler to do some tricks. Making it package private reflects what you have: Access to a class member from another class.

2) How to implement a singleton:

If you ever want to consider serialization, the singleton implementation will get a bit difficult. Joshu Bloch wrote a great section in his book "Effective Java" about implementing singletons. At the end, he concluded to simply use an enum for this, as the Java enum specification provides every charecteristic that is needed in regards to singletons. Of course, that does not use the idiom anymore.

3) Considering design:

In most design decisions, singletons do not have their places anymore. In fact, it could indicate a design issue, if you must place a singleton into your program. Keep in mind: Singletons provide a global acess mechanism to some data or services. And this is not OOP.

这篇关于正确实现按需初始化持有者习语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:53
查看更多