设计模式--单例模式 (6种实现方式)
所谓单例模式,就是采取一定的方法保证整个软件系统,对某个类只存在一个对象实例,且该类只提供一个取得其对象实例的方法。
- 饿汉式单例模式(静态变量)
/**
* 饿汉式
* 线程安全
*/
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getIntance(){
return instance;
}
}
- 饿汉式单例模式(静态代码块)
/**
* 饿汉式
* 线程安全
*/
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton(){}
public static Singleton getIntance(){
return instance;
}
}
- 懒汉式线程不安全的单例模式:
/**
* 懒汉式
* 线程不安全
*/
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getIntance(){
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
- 懒汉式线程安全的单例模式:(但由于同步器,每次都要同步,效率低)
/**
* 懒汉式
*/
public class Singleton {
private static Singleton instance;
private Singleton(){}
/**
* 加入同步器搞定
*/
public static synchronized Singleton getIntance(){
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
- (推荐使用)静态内部类的方式实现单例模式(线程安全,懒加载)
// 外部类被装载时,内部类可能不会立刻装载
// getInstance调用时,内部类开始装载
// 装载时是 线程安全 的,所以静态变量只会初始化一次
public class Singleton {
private Singleton(){}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getIntance(){
return SingletonInstance.INSTANCE;
}
}
- (推荐使用)枚举方式实现单例模式(线程安全,非懒加载,防反序列化)
enum Singleton {
INSTANCE;
public void sayOK() {
System.out.println("ok");
}
}
本文作者:明月照江江
本文链接:https://www.cnblogs.com/gradyblog/p/15357901.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步