zoukankan      html  css  js  c++  java
  • 单例模式之新的想法

    前几天被问到了单例模式对构造函数有什么要求吗?答曰:没什么要求吧?

    回来查了下详细的资料才发现,原来单例模式的实现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);
    	}


    singletonObjects 是单例类中存储当前单例对象的一个Map。在获取单例的时候假设能取到则直接返回。假设没有取到则加锁产生一个对象返回。

    依照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); } }


    然后在使用的时候依据singletonObjects 进行查询并返回相应的对象。


  • 相关阅读:
    Leetcode刷题笔记
    Leetcode刷题笔记
    朋友发来的图片,要制作成身份证复印件,怎么办?
    记录一次MAC连接投影闪屏的问题。
    win10系统 端口查看问题。
    使用Windows命令行reg控制注册表键值
    SVN钩子HOOK设置自动备份,服务本地可以看到所有更新内容。
    报错代码:svn-http status413'requset entity too large
    SVN: Cleanup failed update报错 文件被锁定lock办法,cleanup 失效报错。
    Samba centos7文件共享服务器搭建教程,可以更改任意需求操作配置详解。
  • 原文地址:https://www.cnblogs.com/lxjshuju/p/7073532.html
Copyright © 2011-2022 走看看