单例设计模式

通过单例模式可以保证系统中一个类只有一个实例

饿汉式

 * 有点:保证线程安全。
 * 缺点:性能大大下降
 1 package 单例设计模式;
 2 
 3 public class 饿汉式 {
 4 
 5     /**
 6      * @param args
 7      */
 8     public static void main(String[] args) {
 9         Singleton1 s = Singleton1.getInstance();
10     }
11 }
12 class Singleton1{
13     //1.私有构造方法,其他类无法使用
14     private Singleton1(){}
15     //2.声明引用
16     private static Singleton1 s = new Singleton1();
17     public static Singleton1 getInstance(){
18         return s;
19     }
20 }
View Code

懒汉式

* 有点:保证线程安全

* 缺点:性能大大下降

 1 package 单例设计模式;
 2 
 3 public class 懒汉式 {
 4 
 5     /**
 6      * @param args
 7      */
 8     public static void main(String[] args) {
 9         Singleton2 s = Singleton2.getInstance();
10     }
11 }
12 
13 class Singleton2{
14     //1.私有化构造函数
15     private Singleton2(){}
16     //2.声明变量
17     private static Singleton2 s;
18     //3.为变量实例化
19     public static Singleton2 getInstance(){
20         if(s==null){
21             s = new Singleton2();
22         }
23         return s;
24     }
25 }
View Code

 /*

* 饿汉式和懒汉式的区别
* 1,饿汉式是空间换时间,懒汉式是时间换空间
* 2,在多线程访问时,饿汉式不会创建多个对象,而懒汉式有可能会创建多个对象
*/

第三种

 1 package 单例设计模式;
 2 
 3 public class 第三种 {
 4 
 5     /**
 6      * @param args
 7      */
 8     public static void main(String[] args) { 
 9         Singleton3 s = Singleton3.s;
10     }
11 
12 }
13 class Singleton3{
14     private Singleton3(){}
15     public static final Singleton3 s = new Singleton3();
16 }
View Code
原文地址:https://www.cnblogs.com/2016Study/p/5836163.html