设计模式7,单例模式(下)

目录

基于容器的单例模式

基于ThreadLocal的线程“单例”

单例模式在代码中的应用


基于容器的单例模式

public class ContainerSingleton {
    private static Map<String , Object> singletonMap = new HashMap<>();
    public static void putInstance(String key , Object instance){
        if(!"".equals(key) && key != null && instance != null){
            if(!singletonMap.containsKey(key)){
                singletonMap.put(key , instance);
            }
        }
    }

    public static Object getInstance(String key){
        return singletonMap.get(key);
    }

    private ContainerSingleton(){

    }

}

这种就是用一个map来管理,当然这种方式以刚开始多线程的方式来测试,也是线程不安全的,如果用HashTable线程就是安全的了,但是这样一来资源就会占用很大,所以不太推荐。所以具体用那种还是要根据实际情况来看。

基于ThreadLocal的线程“单例”

这里加引号的单例并不是真正的单例,而是对于线程的单例。

public class ThreadLocalInstance {
    private static final ThreadLocal<ThreadLocalInstance> threadLocal = new ThreadLocal<ThreadLocalInstance>(){
        @Override
        protected ThreadLocalInstance initialValue() {
            return new ThreadLocalInstance();
        }
    };
    private ThreadLocalInstance(){

    }
    public static ThreadLocalInstance getInstance(){
        return threadLocal.get();
    }
}
public class T implements Runnable {
    @Override
    public void run() {
        ThreadLocalInstance instance = ThreadLocalInstance.getInstance();
        System.out.println(Thread.currentThread().getName() + "  " + instance);
    }
}
public class Test {
    public static void main(String[] args) {
        Thread t1 = new Thread(new T());
        Thread t2 = new Thread(new T());
        t1.start();
        t2.start();

        System.out.println(ThreadLocalInstance.getInstance());
        System.out.println(ThreadLocalInstance.getInstance());
        System.out.println(ThreadLocalInstance.getInstance());
        System.out.println(ThreadLocalInstance.getInstance());
        System.out.println(ThreadLocalInstance.getInstance());
        System.out.println(ThreadLocalInstance.getInstance());
    }
}

结果:

可以看出,在同一线程内,获取到的对象是单例的。


单例模式在代码中的应用

Runtime,典型的饿汉式

Desktop

 看一下里面的context#get

这里使用了两个同步锁,容器单例

ErrorContext

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值