单例模式--singleton

单例模式就是说无论程序如何运行,采用单例设计模式永远只会有一个实例化对象产生。

单例实现原理:

(1)构造方法私有化。
(2)创建该类的实例化对象,并将其封装成private static类型。
(3)定义一个静态方法返回该类的实例。

1.饿汉式

 1 /**  
 2  *   
 3  * 单例模式的实现:饿汉式,线程安全 但效率比较低  
 4  */  
 5 public class SingletonTest {   
 6   
 7     private SingletonTest() {   
 8     }   
 9   
10     private static final SingletonTest instance = new SingletonTest();   
11   
12     public static SingletonTest getInstancei() {   
13         return instance;   
14     }   
15   
16 } 

2.懒汉式

 1 /**
 2  * 单例模式的实现:饱汉式,非线程安全
 3  */
 4 public class SingletonTest {
 5     private SingletonTest() {
 6     }
 7 
 8     private static SingletonTest instance;
 9 
10     public static SingletonTest getInstance() {
11         if (instance == null)
12             instance = new SingletonTest();
13         return instance;
14     }
15 }

3.加锁懒汉式

 1 /**
 2  * 线程安全,但是效率非常低
 3  *
 4  * @author vanceinfo
 5  */
 6 public class SingletonTest {
 7     private SingletonTest() {
 8     }
 9 
10     private static SingletonTest instance;
11 
12     public static synchronized SingletonTest getInstance() {
13         if (instance == null)
14             instance = new SingletonTest();
15         return instance;
16     }
17 }

4.双检懒汉式

 1 /**
 2  * 线程安全  并且效率高
 3  */
 4 public class SingletonTest {
 5     private static SingletonTest instance;
 6 
 7     private SingletonTest() {
 8     }
 9     
10     public static SingletonTest getIstance() {
11         if (instance == null) {
12             synchronized (SingletonTest.class) {
13                 if (instance == null) {
14                     instance = new SingletonTest();
15                 }
16             }
17         }
18         return instance;
19     }
20 }  

 5.静态内部类的懒汉式

 1 /**
 2  * 线程安全,懒加载
 3  */
 4 public class SingletonTest {
 5 
 6     private SingletonTest() {
 7     }
 8 
 9     private static class SingletonTestInner {
10         private static final SingletonTest instance = new SingletonTest();
11     }
12 
13 
14     public static SingletonTest getIstance() {
15         return SingletonTestInner.instance;
16     }
17 }

6.枚举

 1 /**
 2  * 线程安全,自动实现序列化机制
 3  */
 4 public enum SingletonTest {
 5     INSTANCE;
 6 
 7     public String getField() {
 8         return field;
 9     }
10 
11     public void setField(String field) {
12         this.field = field;
13     }
14 
15     private String field;
16 }
原文地址:https://www.cnblogs.com/ivy-xu/p/12401306.html