23种设计模式学习之:单例模式

单例模式

保证一个类仅有一个实例,并提供一个访问它的全局访问点。

我们来看下实现单例模式的几种方式:

非线程安全:

1.饿汉模式

public class Singleton {
	private static Singleton instance = new Singleton();
	private Singleton(){
	}
	public static Singleton getInstance(){
		return instance;
	}
}

2.懒汉模式

public class Singleton2 {
	private static Singleton2 instance;
	private Singleton2(){
	}
	public static Singleton2 getInstance(){
		if(instance != null){
		}else{
			instance = new Singleton2();
		}
		return instance;
	}
}

3.懒汉模式改进1

public class Singleton2 {
	private static Singleton2 instance;
	private Singleton2(){
	}
	synchronized public static Singleton2 getInstance(){
		if(instance != null){	
		}else{
			instance = new Singleton2();
		}
		return instance;
	}
}

4.懒汉模式改进2

public class Singleton2 {
	private static Singleton2 instance;
	private Singleton2(){
	}
	public static Singleton2 getInstance(){
		if(instance != null){
		}else{
			synchronized (Singleton2.class) {
				instance = new Singleton2();
			}
		}
		return instance;
	}
}

懒汉模式改进1效率低。懒汉模式改进2同步部分代码块并不能解决线程安全问题,instance = new Singleton2(),语句是分两步执行的,JVM并不保证两个操作的先后顺序。

线程安全:

5.DCL(Double Check Lock)双检查锁机制

public class Singleton3 {
	private volatile static Singleton3 instance;
	private Singleton3(){	
	}
	public static Singleton3 getInstance(){
		if(instance != null){
			
		}else{
			synchronized (Singleton3.class) {
				instance = new Singleton3();
			}
		}
		return instance;
	}
}

6.静态内置类

public class Singleton4 {
	private static class Singleton4Handler{
		private static Singleton4 instance = new Singleton4();
	}
	private Singleton4(){	
	}
	public static Singleton4 getInstance(){
		return Singleton4Handler.instance;
	}
}

7.static代码块

public class Singleton5 {
	private static Singleton5 instance;
	private Singleton5(){
	}
	static{
		instance = new Singleton5();
	}
	public static Singleton5 getInstance(){
		return instance;
	}
}

8.enum枚举

public enum Singleton6 {
	instance;
	private Car car;
	private Singleton6(){
		car = CarFactory.choseMaserati();
	}
	public Car getCar(){
		return car;
	}
}

9.完善enum枚举
前面的枚举,违反了"单一职责原则",进行改进

public class Singleton7{
	public enum Singleton {
		instance;
		private Car car;
		private Singleton(){
			car = CarFactory.choseMaserati();
		}
		public Car getCar(){
			return car;
		}
	}
	public static Car getCar(){
		return Singleton.instance.getCar();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值