单例模式简介
单例模式顾名思义就是保证我们的类对外只提供一个实例,是设计模式中最简单的一种设计思想。
实现单例模式的三种方法
饿汉式
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Sington001 {
private Sington001() {}
private static final Sington001 SINGTON_001 = new Sington001();
public static Sington001 getInstance(){ return SINGTON_001; } }
|
之所以称他懒汉式,是因为他在类加载的时候就已经被实例化,缺点就是不支持多线程,没有调用的时候也会实例化造成内存浪费
懒汉式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class Sington002 {
private Sington002() {}
private static Sington002 SINGTON_002 = null;
public static synchronized Sington002 getInstance(){ if (SINGTON_002==null) { return new Sington002(); } return SINGTON_002; } }
|
懒汉式相比较有一个好处就是第一次调用才初始化,避免内存浪费。而且加锁之后也能保证多线程的安全,缺点就是效率低下
双重校验锁模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class Sington003 {
private Sington003() {}
private static Sington003 SINGTON_003 = null;
public static Sington003 getInstance(){ if (null==SINGTON_003) { synchronized (Sington003.class){ if (null==SINGTON_003) { return new Sington003(); } } } return SINGTON_003; } }
|
这种是对前两种的结合
注意事项
- 其构造方法都是私有的,所以只能自己提供实例,外界不能直接new其对象