当实例的应用场景是单例,并且创建和销毁的开销比较大,长时间应用的实例,考虑用单例模式;
① spring依赖注入时,其注入实例都是单例的
源码 :
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
先从缓存获取bean(this.singletonObjects.get(beanName)),如为null,则单例加锁构造一个实例,保证注入的实例都是单例的,这些实例都是不太容易销毁的,所以这样做节省了重复创建对象的开销;
② 例如jdbc中,DriverManager,其本身是一个管理者角色,用于统筹 Driver的register和获取Connection的衔接,更偏向于面向过程,其根本就没有实例化的必要,所以可以用私有化其构造方法来控制;
源码 :
package java.sql;
....
public class DriverManager {
....
/* Prevent the DriverManager class from being instantiated. */
private DriverManager(){}
....
}
评论区