前几天被问到了单例模式对构造函数有什么要求吗?答曰:没什么要求吧?
回来查了下详细的资料才发现,原来单例模式的实现private 的一个构造函数,目的是不让这个单例的类可以new一个对象出来。
思考了下,事实上不加应该问题也不大,毕竟假设代码上都是一个人在写的话,事实上这样的问题还是能够规避的。可是又发现了其它新的一些想法。
先说下曾经写的单例吧,事实上也非常easy,无非就是一个private static然后用getInstance返回,如今感觉想法确实有点幼稚。
上面说的那个private 的构造函数就不提了。个人感觉有当然最好,可是无也未尝不可。
贴一段spring的源代码看看spring的sigleton怎样写的先
/**
* Return the (raw) singleton object registered under the given name.
* <p>Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
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);
}
依照spring的做法,对于配置文件里的类进行注冊到singletonObjects 中
代码例如以下:
/**
* Add the given singleton object to the singleton cache of this factory.
* <p>To be called for eager registration of singletons.
* @param beanName the name of the bean
* @param singletonObject the singleton object
*/
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
原文:http://www.cnblogs.com/lxjshuju/p/7073532.html