单例模式
Posted Tianyiya H.T.W
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。
应用
- 各种Manager
- 各种Factory
单例模式
饿汉
public class Singleton
private static final Singleton INSTANCE = new Singleton();
private Singleton()
private static Singleton getInstance()
return INSTANCE;
懒汉
public class Singleton
private static Singleton INSTANCE;
private Singleton()
private static synchronized Singleton getInstance()
if (INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
懒汉(双重检锁)
public class Singleton
private static volatile Singleton INSTANCE;
private Singleton()
private static Singleton getInstance()
if (INSTANCE == null)
synchronized (Singleton.class)
if (INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
静态内部类
public class Singleton
private static class Holder
private static final Singleton INSTANCE = new Singleton();
private Singleton()
private static Singleton getInstance()
return Holder.INSTANCE;
枚举
public enum Singleton
INSTANCE;
private static Singleton getInstance()
return INSTANCE;
保护单例
防止序列化
private Object readResolve()
return getInstance();
防止反射
构造器中加入反射拦截代码
心之所向,素履以往 生如逆旅,一苇以航
以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章