美文网首页
单例模式

单例模式

作者: keith666 | 来源:发表于2016-05-18 23:20 被阅读8次

    Intent

    • Ensure a class has only one instance, and provide a global point of access to it.
    • Encapsulated "just-in-time initialization" or "initialization on first use".

    Structure

    Scheme of SingletonScheme of Singleton

    代码:

    // normal single ton, bad for multi-thread
    public class SingleTon {
        private static SingleTon instance;
    
        private SingleTon() {
        }
    
        public SingleTon getInstance() {
            if (instance == null) instance = new SingleTon();
            return instance;
        }
    }
    

    对于多线程的问题:

    1. 加synchronized关键字或加锁,但是性能可能下降100
    // lock
    public class SingleTon {
        private static SingleTon instance;
        Lock lock = new ReentrantLock();
    
        private SingleTon() {
        }
    
        public SingleTon getInstance() {
            lock.lock();
            try {
                if (instance == null) instance = new SingleTon();
                return instance;
            } finally {
                lock.unlock();
            }
    
        }
    }
    
    1. 使用"急切"创建实例,不用延迟创建(Recommanded)
    // Initialization on Demand Holder
    public class SingleTon {
        private static SingleTon instance = new SingleTon();
    
        private SingleTon() {
        }
    
        public SingleTon getInstance() {
            return instance;
        }
    }
    
    1. 使用"双重检查枷锁",在getInstance()中减少使用同步
    // double-checked locking
    public class SingleTon {
        private volatile static SingleTon instance = new SingleTon();
    
        private SingleTon() {
        }
    
        public SingleTon getInstance() {
            if (instance == null) {
                synchronized (SingleTon.class) {
                    if (instance == null) instance = new SingleTon();
                }
            }
            return instance;
        }
    }
    

    Refenrence

    1. Design Patterns
    2. Head First 设计模式

    相关文章

      网友评论

          本文标题:单例模式

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