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

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.

主站蜘蛛池模板: 故城县| 武冈市| 德安县| 凤山县| 古交市| 澎湖县| 桐乡市| 拉孜县| 恩平市| 凌源市| 滨州市| 湛江市| 吴旗县| 密云县| 奈曼旗| 宁化县| 安塞县| 柯坪县| 克什克腾旗| 墨江| 庆元县| 武冈市| 额尔古纳市| 根河市| 临漳县| 朝阳市| 本溪| 阿图什市| 手机| 临高县| 电白县| 梅河口市| 健康| 化州市| 曲周县| 清水县| 民县| 鹿邑县| 卓资县| 阳江市| 白银市|