单例模式:饿汉式、懒汉式;线程安全的单例模式创建的6种方式

单例模式

单例模式Singleton是一种创建型模式,指某个采用Singleton单例模式,则这个类在同一个

JVM上,只能产生一个实例供外部访问,并且仅提供一个全局的访问方式。

懒汉式

懒汉式线程不安全

public class Singleton1 {
	private static Singleton1 instance;
	
	// 构造方法私有化!!!
	private Singleton1() {};
	
	public static Singleton1 getInstance() {
		if(instance == null) {
			instance = new Singleton1();
		}
		return instance;
	}
}

饿汉式

饿汉式线程安全

public class Singleton2 {
	private static final Singleton2 instance = new Singleton2();
	// 构造方法私有化
	private Singleton2() {};

	public static Singleton2 getInstance() {
		return instance;
	}
}

线程安全的单例模式

  1. 饿汉式线程安全
  2. 全局锁线程安全
  3. 静态代码块创建单例对象线程安全
  4. 双重校验锁实现线程安全
  5. 静态内部类实现线程安全的单例模式
  6. 内部枚举类实现线程安全
  • 全局锁

    public class Singleton3 {
    	private static Singleton3 instance;
    
    	// 构造方法私有化
    	private Singleton3() {};
    
    	// 通过synchronized添加全局锁实现线程安全
    	public static synchronized Singleton3 getInstance() {
    		if (instance == null) {
    			instance = new Singleton3();
    		}
    		return instance;
    	}
    }
    
  • 静态代码块

    public class Singleton4 {
    	private static final Singleton4 instance;
    	
    	// 静态代码块创建单例对象
    	static {
    		instance = new Singleton4();
    	}
    	
    	// 构造方法私有化
    	private Singleton4(){}
      
    	public static Singleton4 getInstance() {
    		return instance;
    	}
    }
    
  • 双重校验锁

    public class Singleton5 {
    
    	private static Singleton5 instance;
    
    	private Singleton5() {
    	}
    
    	public static Singleton5 getInstance() {
    		if (instance == null) {
    			synchronized (Singleton5.class) {
    				if (instance == null) {
    					instance = new Singleton5();
    				}
    			}
    		}
    		return instance;
    	}
    }
    
  • 静态内部类

    public class Singleton6 {
    	// 构造方法私有化
    	private Singleton6() {};
    	
    	// 静态内部类
    	private static class SingletonHolder{
    		// 创建单例对象
    		private static Singleton6 instance = new Singleton6();
    	}
    	public static Singleton6 getInstance() {
    		return Singleton6.SingletonHolder.instance;
    	}
    }
    
  • 静态枚举类

    public class Singleton7 {
    	private Singleton7() {}
    	
    	// 内部枚举类
    	enum SingletonEnum{
    		INSTANCE;
    		
    		// 单例对象
    		private Singleton7 instance;
        
    		private SingletonEnum() {
    			instance = new Singleton7();
    		}
        
    		private static Singleton7 getInstance() {
    			return SingletonEnum.INSTANCE.instance;
    		}
    	}
    }	
    
  • 45
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeMonkey-D

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值