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

  • Spring 5 Design Patterns
  • Dinesh Rajput
  • 254字
  • 2021-07-08 09:59:33

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.

主站蜘蛛池模板: 札达县| 阳朔县| 舟曲县| 英山县| 平度市| 广南县| 六枝特区| 桃园市| 江川县| 新化县| 进贤县| 玉环县| 武安市| 左权县| 贡嘎县| 彭州市| 巴林左旗| 屯留县| 宁陕县| 德州市| 青浦区| 宾川县| 孙吴县| 天柱县| 苍溪县| 手游| 博罗县| 高尔夫| 安阳市| 湖口县| 襄城县| 乐都县| 丰镇市| 定南县| 嘉祥县| 邹城市| 通道| 克东县| 安徽省| 邛崃市| 措美县|