打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
设计模式-单例模式

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

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

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

 1 /** 2  * 懒汉模式 3  * @author maikec 4  * @date 2019/5/11 5  */ 6 public final class SingletonLazy { 7     private static SingletonLazy singletonLazy; 8     private SingletonLazy(){} 9     public static SingletonLazy getInstance(){10         if (null == singletonLazy){11             ReentrantReadWriteLock.WriteLock lock = new ReentrantReadWriteLock().writeLock();12             try {13                 if (lock.tryLock()){14                     if (null == singletonLazy){15                         singletonLazy = new SingletonLazy();16                     }17                 }18             }finally {19                 lock.unlock();20             }21 22 //            synchronized (SingletonLazy.class){23 //                if (null == singletonLazy){24 //                    singletonLazy = new SingletonLazy();25 //                }26 //            }27         }28         return singletonLazy;29     }30 }

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

 1 package singleton; 2 /** 3  * 饿汉模式 4  * @author maikec 5  * @date 2019/5/11 6  */ 7 public class SingletonHungry { 8     private static SingletonHungry ourInstance = new SingletonHungry(); 9 10     public static SingletonHungry getInstance() {11         return ourInstance;12     }13 14     private SingletonHungry() {15     }16 }

附录

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

声明

引用该文档请注明出处

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
5.2.3 单例模式示例代码
设计模式——单例模式(Singleton)
初学者第67节多线程之单例模式(十)
设计模式-----单例模式(Singleton Pattern)
设计模式:单例模式 (关于饿汉式和懒汉式)
设计模式之单例模式
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服