欢迎来到大鹏的IT世界,本文给大家分享的是设计模式之单例模式。保持专注,持续学习,你就比别人强。
一、概念:
单例模式:看名字就很清楚它的意思了,就是保证一个类仅有一个实例,并提供一个访问它的全局访问点。
二、UML图:
三、单例模式有三个特征:
1.私有化构造函数。目的是防止外界new实例。
2.一个私有的静态全局变量。
3.一个静态公有方法,对外提供它的唯一实例。
四、单例模式的不同实现:
1.懒汉式,线程不安全
描述:这种实现最大的问题就是不支持多线程。
代码实现:
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
2.懒汉式,线程安全
描述:加上synchronized保证线程安全,但是性能很低。
代码实现:
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
3.饿汉式,线程安全
描述:这种方式比较常用,但容易产生垃圾对象。它的优点就是没有加锁,执行效率会提高。缺点是类加载时就初始化,浪费内存。它是基于 classloder 机制避免了多线程的同步问题。
代码实现:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
4.双重锁定
描述:这种方式采用双锁机制,保证线程安全并且保持高性能。
代码实现:
public class Singleton {
private volatile static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
最后:
一般情况下,不建议使用第 1 种和第 2 种懒汉方式,建议使用第 3 种饿汉式和第 4 种双重锁定方式。用的最多的当然是第3种饿汉式,以为写起来简单嘛,哈哈。
欢迎大家的观看,希望能帮到大家。