设计模式-单例模式

单例模式指在系统中有且仅有一个对象实例,比如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设计模式案例

声明

引用该文档请注明出处

原文地址:https://www.cnblogs.com/imaikce/p/10855814.html