单例模式
定义: 确保应用中应用单例模式的类只能有一个实例
实现:
- 构造方法私有化,使其不能在外部通过使用 new 关键字来实例化对象
- 在类产生唯一一个 private static 的实例化对象
- 定义一个静态方法返回该对象
具体实现一: 饿汉模式(线程安全)
在类加载时就创建对象
优点: 实现简单,线程安全
缺点: 在类加载时就实例化了对象,使此对象一直存在,当类被卸载时才会释放内存,故在一定情况下消耗内存
public class TestOne {
//实例化一个私有的对象实例
private static final TestOne testOne = new TestOne();
//构造方法私有化
private TestOne() {}
//定义静态方法返回实例
public static TestOne getInstance() {
return testOne;
}
}
具体实现二: 懒汉模式(非线程安全)
在类中定义类属性,在 get 方法中实例化对象,即在调用才实例化对象
优点: 实现简单,只有在调用时才会实例化对象,内存占用少
缺点: 线程不安全
public class TestTwo {
//定义一个私有的对象
private static TestTwo testTwo;
//构造方法私有化
private TestTwo() {}
//定义一个静态方法返回实例
public static TestTwo getInstance() {
if (testTwo == null) {
testTwo = new TestTwo(); //在 get 方法中实例化对象
}
return testTwo;
}
}
具体实现三: 懒汉模式(线程安全)
使用 synchronized 关键字修饰 get 方法,使其同步
优点: 保证了懒汉模式的线程安全
缺点: synchronize 效率的
public class TestThree {
//定义私有类类型属性
private static TestThree testThree;
//构造方法私有化
private TestThree() {}
//定义静态方法返回实例化对象,用 synchronized 关键字修饰使其线程安全
public static synchronized TestThree getInstance() {
if (testThree == null) {
testThree = new TestThree();
}
return testThree;
}
}
具体实现四: DCL双检查锁机制(最完美实现)
优点: 效率高,线程安全,多线程操作原子性
缺点: 没有
public class TestFour {
//定义类类型属性
private static TestFour testFour;
//构造方法私有化
private TestFour() {}
//定义一个静态方法返回对象
public static TestFour getInstance() {
if (testFour == null) { //先判断对象是否存在
synchronized (TestFour.class) { //当此线程得到锁时
if (testFour == null) {
testFour = new TestFour();
}
}
}
return testFour;
}
}
Death pledge

本文深入解析单例模式的四种实现方式:饿汉模式、懒汉模式(非线程安全)、懒汉模式(线程安全)及DCL双检查锁机制。详细介绍了每种方式的优缺点,帮助读者理解并选择适合的单例模式实现。
101万+

被折叠的 条评论
为什么被折叠?



