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

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.

主站蜘蛛池模板: 沾化县| 沂南县| 同江市| 德江县| 鹤山市| 烟台市| 环江| 佛冈县| 克什克腾旗| 七台河市| 弋阳县| 成安县| 荣昌县| 天柱县| 沁源县| 乌兰察布市| 麻城市| 凤凰县| 东乡族自治县| 陆川县| 凤冈县| 讷河市| 芜湖市| 开平市| 介休市| 肃宁县| 迁西县| 盘锦市| 高雄县| 石嘴山市| 阿克苏市| 康乐县| 巫溪县| 惠东县| 长汀县| 中西区| 双江| 泊头市| 无为县| 兴化市| 泰和县|