最近在学习设计模式,之前断断续续的看过好多,自己也没有专门的练习和深入了解过,一直感觉对应设计模式相关的东西还是处于懵懂状态,这次下定决心好好的学习一下,所以做一个笔记用来督促自己。
资料收集与以下网站,如有冒犯,烦请告知
https://www.cnblogs.com/garryfu/p/7976546.html
http://c.biancheng.net/design_pattern/
https://www.runoob.com/design-pattern/design-pattern-tutorial.html
简单说明
- 单例模式可以维持系统内某个类只有一个实例。
- 在系统中,日志对象、对话框、打印机驱动等通常的会设计成单例模式。
- 单例模式主要用来保持状态的统一,避免不同请求同时调用时,会造成状态混乱的情况。
- 编不下去了!!!我承认我就是个菜狗
简单理解
- 类的构造器私有化
- 内部实例化
- 外部全局访问
静态常量实现 饿汉式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class Singleton { private Singleton() { } private static final Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } public void print() { System.out.println("创建成功"); } }
class a { public static void main(String[] args) { Singleton.getInstance().print(); } }
|
静态代码块实现 - 饿汉式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class Singleton{ private Singletonton(){ } private static Singleton instance; static{ instance = new Singleton(); } public static Singleton getInstance(){ return instance; } }
|
模式特点
- 饿汉式单例,在类加载的时候就已经创建好了一个静态对象供系统使用,以后不再改变,所以是线程安全的,可以直接用于多线程
线程不安全的 - 懒汉式
1 2 3 4 5 6 7 8 9 10 11
| public class Singleton{ private static Singleton instance; private Singleton(){ } public static Singleton getInstance(){ if(null == instance) instance = new Singleton(); return instance; } }
|
线程安全的 - 懒汉式
1 2 3 4 5 6 7 8 9 10 11
| public class Singleton{ private static Singleton instance; private Singleton(){ } public static synchronized Singleton getInstance(){ if(null == instance) instance = new Singleton(); return instance; } }
|
模式特点
- 懒汉式单例模式,使用了延迟加载的方式,只有在调用
getInstance()
方法时才会进行实例化 - 第一种模式虽然可以做到延时加载,但是在多线程的使用场景中容易出现多实例的情况
- 第二种模式添加了
synchronized
同步锁,使得该方法变成了线程安全的方式,但是多数情况下是不需要同步的,所以该模式运行效率很低。
双重校验锁模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class Singleton { private Singleton(){ } private static Singleton instance; public static Singleton getInstance(){ if(null == instance){ synchronized(Singleton.class){ if(null == instance){ instance = new Singleton(); } } } return instance; } }
|
模式特点
- 延迟加载
- 第一次判断
instance
为空的时候,会进入同步锁,进入同步锁的线程根据再次判断的情况,实例化Singleton
,第二次访问的时候,instance
不为空,则不进入同步锁,保证了执行效率。
静态内部类模式
1 2 3 4 5 6 7 8 9 10 11
| public class Singleton{ private Singleton(){ } private static class SingletonHolder{ private static Singleton instance = new Singleton(); } public static Singleton getInstance(){ return SingletonHolder.instance; } }
|
模式特点
- 多线程并发下,线程是安全的
- 但是遇到序列号对象时,默认的方式运行得到的结果就是多例的。
枚举模式
1 2 3 4 5 6 7 8 9 10 11 12 13
| public enum Singleton{ INSTANCE; private String test = "singleton"; public void print(){ System.out.println(a); } }
public test{ public static void main(String[] args){ Singleton.INSTANCE.print(); } }
|