美文网首页
开发中写单例的正确姿势

开发中写单例的正确姿势

作者: jackzhang1990 | 来源:发表于2017-05-18 17:58 被阅读13次

public class SingletonClass {
private static volatile SingletonClass sSoleInstance;

    //private constructor.    
    private SingletonClass() {
        //Prevent form the reflection api.        
        if (sSoleInstance != null) {
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        }
    }

    public static SingletonClass getInstance() {
        //Double check locking pattern        
        if (sSoleInstance == null) { //Check for the first time
            synchronized (SingletonClass.class) {   //Check for the second time.                
                // if there is no instance available... create new one                
                if (sSoleInstance == null)
                    sSoleInstance = new SingletonClass();
            }
        }
        return sSoleInstance;
    }
}

单例模式使用中常见错误:
1.getInstance()不要加锁,
原因:
【1】锁开销会影响性能
【2】如果sSoleInstance已经初始化了,锁机制就不需要了。
2.volatile:可以保证写入操作在读取操作之前发生。

public class SingletonClass implements Serializable {

    private static volatile SingletonClass sSoleInstance;

    //private constructor.    
    private SingletonClass() {
        //Prevent form the reflection api.保证该私有构造函数只会执行一次,即第一次:sSoleInstance为null的时候。        
        if (sSoleInstance != null) {
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        }
    }

    public static SingletonClass getInstance() {
        if (sSoleInstance == null) {
            //if there is no instance available... create new one            
            synchronized (SingletonClass.class) {
                if (sSoleInstance == null)
                    sSoleInstance = new SingletonClass();
            }
        }

        return sSoleInstance;
    }

    //Make singleton from serialize and deserialize operation.    
    protected SingletonClass readResolve() {
        return getInstance();
    }
}

上面写法可以保证:该类事线程,反射,序列化都是安全的。

再谈谈为什么使用单例:
1.控制对象的创建,限制对象的数量只有一个。
2.单例允许只有一个入口来创建对象。
3.常用在控制资源,比如:数据库连接等等。
4.单例的写法比较多,根据不同的情况进行不同的写法,基本围绕上面给出的写法。

相关文章

网友评论

      本文标题:开发中写单例的正确姿势

      本文链接:https://www.haomeiwen.com/subject/nuasxxtx.html