盒子
盒子
文章目录
  1. 1. 饿汉式单例
  2. 2. 懒汉式单例
  3. 3. 双重检查锁实现
  4. 4. 静态内部类实现
  5. 5. 枚举方式实现

单例模式

单例模式:确保一个类只有一个实例,并提供一个全局访问点

1. 饿汉式单例

1
2
3
4
5
6
7
8
9
public class HungrySingleton {
private static HungrySingleton instance = new HungrySingleton();

private HungrySingleton() {};

public static HungrySingleton getInstance() {
return instance;
}
}

2. 懒汉式单例

1
2
3
4
5
6
7
8
9
10
11
12
public class LazySingleton {
private static LazySingleton instance;

private LazySingleton() {};

public static synchronized LazySingleton getInstance() {
if (null == instance) {
instance = new LazySingleton();
}
return instance;
}
}

3. 双重检查锁实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class DoubleCheckedSingleton {
private volatile static DoubleCheckedSingleton instance;

private DoubleCheckedSingleton() {};

public static DoubleCheckedSingleton getInstance() {
if (null == instance) {
synchronized(DoubleCheckedSingleton.class) {
if (null == instance) {
instance = new DoubleCheckedSingleton();
}
}
}
return instance;
}
}

4. 静态内部类实现

1
2
3
4
5
6
7
8
9
10
11
12
public class Singleton {

private Singleton() {};

public static Singleton getInstance() {
return SingletonHolder.singleton;
}

private static class SingletonHolder {
private static final Singleton singleton = new Singleton();
}
}

5. 枚举方式实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class EnumSingleton {

public enum ResourceInstance {
INSTANCE;
private Resource resource;

ResourceInstance() {
this.resource = new Resource();
}

public Resource getResource() {
return this.resource;
}
}
}

class Resource {}
支持一下
扫一扫,支持沈健
  • 微信扫一扫
  • 支付宝扫一扫