设计模式——单例模式

286 阅读1分钟

最新修改已更新到github

单例模式指在系统中有且仅有一个对象实例,比如Spring的Scope默认就是采用singleton。
单例模式的特征是:1、确保不能通过外部实例化(确保私有构造方法)2、只能通过静态方法实例化

懒汉模式——只有需要才创建实例

懒汉模式需要注意到多线程问题

/**
 * 懒汉模式
 * @author maikec
 * @date 2019/5/11
 */
public final class SingletonLazy {
    private static SingletonLazy singletonLazy;
    private SingletonLazy(){}
    public static SingletonLazy getInstance(){
        if (null == singletonLazy){
            ReentrantReadWriteLock.WriteLock lock = new ReentrantReadWriteLock().writeLock();
            try {
                if (lock.tryLock()){
                    if (null == singletonLazy){
                        singletonLazy = new SingletonLazy();
                    }
                }
            }finally {
                lock.unlock();
            }

//            synchronized (SingletonLazy.class){
//                if (null == singletonLazy){
//                    singletonLazy = new SingletonLazy();
//                }
//            }
        }
        return singletonLazy;
    }
}

饿汉模式——初始化类时就创建实例

package singleton;
/**
 * 饿汉模式
 * @author maikec
 * @date 2019/5/11
 */
public class SingletonHungry {
    private static SingletonHungry ourInstance = new SingletonHungry();

    public static SingletonHungry getInstance() {
        return ourInstance;
    }

    private SingletonHungry() {
    }
}

附录

zh.wikipedia.org/wiki/单例模式#J… 维基关于单例模式
github.com/maikec/patt… 个人GitHub设计模式案例

声明

引用该文档请注明出处