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

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.

主站蜘蛛池模板: 承德县| 通江县| 若羌县| 普兰店市| 临潭县| 山阳县| 河源市| 襄城县| 高淳县| 河西区| 盐源县| 团风县| 抚顺县| 蓬溪县| 交口县| 珠海市| 巨鹿县| 黄大仙区| 三台县| 广灵县| 瑞金市| 道真| 徐汇区| 恩施市| 高州市| 沐川县| 敦煌市| 怀宁县| 威远县| 武隆县| 清水县| 新闻| 龙门县| 增城市| 永新县| 将乐县| 永城市| 红安县| 梁平县| 上杭县| 蚌埠市|