文章目录
一、单例模式定义
类型: 创建型模式
介绍: 确保一个类只有一个实例,并提供了一个全局访问点来访问该实例。
目的: 避免一个全局使用的类频繁地创建与销毁。
注意:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
二、例子
单例模式在JAVA有多种实现方式。
根据不同实现还分为懒汉式和饿汉式。
- 饿汉式:不管有没有使用都会创建对象。
- 懒汉式:第一次使用时才创建对象。
2.1 双检锁/双重校验锁(DCL,即 double-checked locking)
public class Singleton {
private Singleton (){}
private volatile static Singleton singleton;
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
2.2 基于枚举的单例模式
public enum SingleObject {
INSTANCE
}
2.3 JDK源码——Runtime
基于静态实例实现的饿汉式单例模式
public class Runtime {
private static final Runtime currentRuntime = new Runtime();
private Runtime() {}
public static Runtime getRuntime() {
return currentRuntime;
}
}
2.4 Spring源码——DefaultSingletonBeanRegistry
Spring的DefaultSingletonBeanRegistry单例模式是采用了双检锁实现,但并非23种设计模式的单例模式。
如果只使用Spring容器创建单例对象确实可以保证对象唯一,但是这个单例是可以被破坏,比如我们手动new一个…
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
private final Map<String, Object> singletonObjects = new ConcurrentHashMap(256);
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap(16);
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && this.isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
synchronized(this.singletonObjects) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
ObjectFactory<?> singletonFactory = (ObjectFactory)this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
}
三、其他设计模式
创建型模式
结构型模式
行为型模式
- 1、设计模式——访问者模式(Visitor Pattern)+ Spring相关源码
- 2、设计模式——中介者模式(Mediator Pattern)+ JDK相关源码
- 3、设计模式——策略模式(Strategy Pattern)+ Spring相关源码
- 4、设计模式——状态模式(State Pattern)
- 5、设计模式——命令模式(Command Pattern)+ Spring相关源码
- 6、设计模式——观察者模式(Observer Pattern)+ Spring相关源码
- 7、设计模式——备忘录模式(Memento Pattern)
- 8、设计模式——模板方法模式(Template Pattern)+ Spring相关源码
- 9、设计模式——迭代器模式(Iterator Pattern)+ Spring相关源码
- 10、设计模式——责任链模式(Chain of Responsibility Pattern)+ Spring相关源码
- 11、设计模式——解释器模式(Interpreter Pattern)+ Spring相关源码