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

Sample implementation of the Singleton design pattern

In the following code example, I will be creating a class with a method to create an instance of this class if one does not exist. If the instance is already present, then it will simply return the reference of that object. I have also taken thread safety into consideration, and so I have used a synchronized block here before creating the object of that class.

Let's check out the UML diagram for the Singleton design pattern:

    package com.packt.patterninspring.chapter2.singleton.pattern; 
    public class SingletonClass { 
      private static SingletonClass instance = null; 
      private SingletonClass() { 
      } 
      public static SingletonClass getInstance() { 
        if (instance == null) { 
          synchronized(SingletonClass.class){   
               if (instance == null) { 
                  instance = new SingletonClass(); 
               } 
          } 
        } 
       return instance; 
      } 
    } 
  } 

One thing to be noted in the preceding code is that I have written a private constructor of the SingletonClass class to make sure that there is no way to create the object of that class. This example is based on lazy initialization, which means that the program creates an instance on demand the first time. So you could also eagerly instantiate the object to improve the runtime performance of your application. Let's see the same SingletonClass with eager initialization:

    package com.packt.patterninspring.chapter2.singleton.pattern; 
    public class SingletonClass { 
      private static final SingletonClass INSTANCE = 
new SingletonClass(); private SingletonClass() {} public static SingletonClass getInstance() { return INSTANCE; } }

Now that we've seen the singleton design pattern, let's turn to a different variant of it--the Prototype design pattern.

主站蜘蛛池模板: 伊宁市| 桃江县| 黄平县| 财经| 苍溪县| 莆田市| 涿鹿县| 平定县| 常德市| 囊谦县| 夏邑县| 房产| 万年县| 苗栗县| 大安市| 金堂县| 若羌县| 曲周县| 舒城县| 张家港市| 开阳县| 聂拉木县| 调兵山市| 赤壁市| 渝中区| 文安县| 兴化市| 浪卡子县| 隆昌县| 东乡县| 湘潭市| 通州市| 鹿邑县| 张家港市| 克东县| 客服| 六枝特区| 长武县| 永善县| 光山县| 东宁县|