当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 设计模式 - 单例模式(Singleton Pattern)

设计模式 - 单例模式(Singleton Pattern)

2018年11月29日  | 移动技术网IT编程  | 我要评论
单例模式 介绍 模式:创建型 意图:保证一个类只有一个实例,并提供一个访问它的全局访问点 解决:一个全局使用的类频繁地创建与销毁 场景: 唯一序列号 web中的计数器 I/O与数据库的连接 …… 唯一序列号 web中的计数器 I/O与数据库的连接 …… 实现方式 饿汉式 :静态加载,线程安全 饿汉式 ...

单例模式

介绍

  • 模式:创建型
  • 意图:保证一个类只有一个实例,并提供一个访问它的全局访问点
  • 解决:一个全局使用的类频繁地创建与销毁
  • 场景:
    • 唯一序列号
    • web中的计数器
    • i/o与数据库的连接
    • ……  

实现方式

  • 饿汉式 :静态加载,线程安全

 1 /**
 2  * 单例模式:饿汉式
 3  * 是否lazy初始化:否
 4  * 是否多线程安全:是
 5  */
 6 public class singleton {
 7 
 8     private static singleton singleton = new singleton();
 9 
10     // 构造器私有
11     private singleton() {
12     }
13 
14     // 实例方法
15     public static singleton getinstance() {
16         return singleton;
17     }
18 }
singleton.java
  • 懒汉式:单校验,线程不安全

 1 /**
 2  * 单例模式:懒汉式
 3  * 是否lazy初始化:是
 4  * 是否多线程安全:否
 5  */
 6 public class singleton {
 7 
 8     private static singleton singleton;
 9 
10     // 构造器私有
11     private singleton() {
12 
13     }
14 
15     // 实例方法
16     public static singleton getinstance() {
17         if (singleton == null) {
18             return new singleton();
19         }
20         return singleton;
21     }
22 }
sington.java
  • 懒汉式:实例方法同步锁,线程安全

 1 /**
 2  * 单例模式:懒汉式
 3  * 是否lazy初始化:是
 4  * 是否多线程安全:是
 5  */
 6 public class singleton {
 7 
 8     private static singleton singleton;
 9 
10     // 构造器私有
11     private singleton() {
12 
13     }
14 
15     // 实例方法
16     public static synchronized singleton getinstance() {
17         if (singleton == null) {
18             return new singleton();
19         }
20         return singleton;
21     }
22 }
sington.java
  • 懒汉式:双检锁/双重校验锁(dcl,double-checked locking),线程安全

 1 /**
 2  * 单例模式:懒汉式
 3  * 是否lazy初始化:是
 4  * 是否多线程安全:是
 5  */
 6 public class singleton {
 7 
 8     private static volatile singleton singleton;
 9 
10     // 构造器私有
11     private singleton() {
12 
13     }
14 
15     // 实例方法
16     public static singleton getinstance() {
17         if (singleton == null) {
18             synchronized (singleton.class) {
19                 if (singleton == null) {
20                     return new singleton();
21                 }
22             }
23         }
24         return singleton;
25     }
26 }
sington.java
  • 登记式/静态内部类:线程安全

 1 /**
 2  * 单例模式:登记式/静态内部类
 3  * 是否lazy初始化:是
 4  * 是否多线程安全:是
 5  */
 6 public class singleton {
 7 
 8     // 静态内部类持有
 9     private static class singletonholder {
10         private static final singleton singleton = new singleton();
11     }
12 
13     // 构造器私有
14     private singleton() {
15 
16     }
17 
18     // 实例方法
19     public static singleton getinstance() {
20         return singletonholder.singleton;
21     }
22 }
sington.java
  • 枚举:线程安全

1 /**
2  * 单例模式:枚举
3  * 是否lazy初始化:否
4  * 是否多线程安全:是
5  */
6 public enum singleton {
7     singleton
8 }
singleton.java

 

 

资料来源:阿里云大学 - 设计模式

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网