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

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.

主站蜘蛛池模板: 盐边县| 常山县| 博罗县| 贡嘎县| 霍山县| 乐都县| 东兴市| 化德县| 钟山县| 琼结县| 寿光市| 涟水县| 安义县| 施甸县| 滨海县| 隆德县| 龙胜| 石林| 乌恰县| 米泉市| 广河县| 兴安盟| 虎林市| 商洛市| 康定县| 印江| 北辰区| 澄迈县| 牟定县| 曲周县| 溧阳市| 调兵山市| 长阳| 宿迁市| 南郑县| 黄山市| 仁布县| 禄劝| 疏勒县| 广宗县| 镶黄旗|