官术网_书友最值得收藏!

Singletons – being one and only one

A singleton is a class of which only a single instance can exist. How do we prevent anyone from creating yet another instance? The solution is to make the constructor inaccessible. Here it is:

public class Singleton {
      // Eager initialization
  private static final Singleton instance = new Singleton(); // 1
 
  private Singleton() { // 2
  /* client code cannot create instance */
 }
 
      // Static factory method 
 public static Singleton getInstance() { // 3
  return instance;
 }

 // Driver code
 public static void main(String[] args) {
  System.out.println(Singleton.getInstance());
  System.out.println(Singleton.getInstance());
 }
}

Dissecting the code:

  • At 1, the static initializer creates the instance—also the final keyword ensures that the instance cannot be redefined.
  • At 2, the constructor access is private, so only the class methods can access it.
  • At 3, the public factory method gives access to the client code.

If you run the Java program, you will see the same object reference printed twice.

A singleton has many forms. There is a null check version and a double-checked locking pattern version. The preceding version is a nicer way—it is the eager-initialized version though.

Note

There is a related pattern called Monostate. Refer to http://www.objectmentor.com/resources/articles/SingletonAndMonostate.pdf for more on this.

主站蜘蛛池模板: 辽阳县| 图们市| 尚志市| 日土县| 滦平县| 锡林郭勒盟| 林芝县| 和硕县| 承德市| 成安县| 盘锦市| 且末县| 潼关县| 焦作市| 临澧县| 监利县| 来凤县| 辽中县| 祁连县| 章丘市| 宝清县| 报价| 庄浪县| 甘洛县| 古田县| 兰州市| 阜阳市| 沧源| 满洲里市| 武功县| 锡林浩特市| 天等县| 容城县| 鄱阳县| 砚山县| 云安县| 磴口县| 百色市| 鸡泽县| 永和县| 古田县|