【设计模式】创建型模式:单例模式
文章目录
- 一、【设计模式】创建型模式:单例模式
- 1、懒汉式,线程不安全
- 2、懒汉式,线程安全
- 3、饿汉式,线程安全
- 4、双检锁/双重校验锁,线程安全
- 5、登记式/静态内部类,线程安全
- 6、枚举,线程安全
一、【设计模式】创建型模式:单例模式
保证一个类仅有一个实例,并提供一个访问它的全局访问点
1、懒汉式,线程不安全
package cn.tellsea.designmode;
/**
* 单例模式
*
* @author Tellsea
* @date 2022/9/29
*/
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2、懒汉式,线程安全
增加了 synchronized 修饰方法
package cn.tellsea.designmode;
/**
* 单例模式
*
* @author Tellsea
* @date 2022/9/29
*/
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
3、饿汉式,线程安全
package cn.tellsea.designmode;
/**
* 单例模式
*
* @author Tellsea
* @date 2022/9/29
*/
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static synchronized Singleton getInstance() {
return instance;
}
}
4、双检锁/双重校验锁,线程安全
这种方式采用双锁机制,安全且在多线程情况下能保持高性能
package cn.tellsea.designmode;
/**
* 单例模式
*
* @author Tellsea
* @date 2022/9/29
*/
public class Singleton {
private static volatile Singleton singleton;
private Singleton() {
}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
5、登记式/静态内部类,线程安全
种方式能达到双检锁方式一样的功效,但实现更简单。对静态域使用延迟初始化,应使用这种方式而不是双检锁方式。这种方式只适用于静态域的情况,双检锁方式可在实例域需要延迟初始化时使用
package cn.tellsea.designmode;
/**
* 单例模式
*
* @author Tellsea
* @date 2022/9/29
*/
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {
}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
6、枚举,线程安全
这种实现方式还没有被广泛采用,但这是实现单例模式的最佳方法。它更简洁,自动支持序列化机制,绝对防止多次实例化
package cn.tellsea.designmode;
/**
* 单例模式
*
* @author Tellsea
* @date 2022/9/29
*/
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}