[Design Mode] - Singleton singleton

  Preface: [ Mode Overview ] ---------- by xingoo

  Intention mode

  Ensure that only one instance of the class, and can be used by the application global. To ensure this, we need this class to create their own objects, and outside there are public call methods.

  Mode structure

  Singleton Singleton interior contains an object itself. And when the private constructor.

  scenes to be used

  When only one instance of the class, and can be accessed from a fixed access point.

  Code structure

  [Mode] starving by defining Static variables, when the class is loaded, the static variables are initialized.

 1 package com.xingoo.eagerSingleton;
 2 class Singleton{
 3     private static final Singleton singleton = new Singleton();
 4     /**
 5      * 私有构造函数
 6      */
 7     private Singleton(){
 8         
 9     }
10     /**
11      * 获得实例
12      * @return
13      */
14     public static Singleton getInstance(){
15         return singleton;
16     }
17 }
18 public class test {
19     public static void main(String[] args){
20         Singleton.getInstance();
21     }
22 }

 

  [Lazy mode]

 1 package com.xingoo.lazySingleton;
 2 class Singleton{
 3     private static Singleton singleton = null;
 4     
 5     private Singleton(){
 6         
 7     }
 8     /**
 9      * 同步方式,当需要实例的才去创建
10      * @return
11      */
12     public static synchronized Singleton getInstatnce(){
13         if(singleton == null){
14             singleton = new Singleton();
15         }
16         return singleton;
17     }
18 }
19 public class test {
20     public static void main(String[] args){
21         Singleton.getInstatnce();
22     }
23 }

 

Reproduced in: https: //my.oschina.net/u/204616/blog/545034

Guess you like

Origin blog.csdn.net/weixin_34391854/article/details/91989480