黑马程序员技术交流社区
标题:
单例设计模式的第三种实现方式
[打印本页]
作者:
班凤飞
时间:
2015-3-1 08:35
标题:
单例设计模式的第三种实现方式
视频里面毕姥爷只讲了懒汉式和饿汉式两种,还有一种双重锁模式,这个会在下面的考试里面考吗
作者:
Ansel
时间:
2015-3-1 09:44
用synchronized是为了解决懒汉式的缺点,跟后面的多线程有关。都掌握了就行了。
作者:
小泽
时间:
2015-3-1 09:54
那个也是懒汉式,不过就是用在多线程中的线程安全的懒汉式。
作者:
alvis2015
时间:
2015-3-1 10:04
/**
* 饿汉式
* @author Administrator
*
*/
class EagerSingleton {
private static EagerSingleton instance = new EagerSingleton();
private EagerSingleton(){}
public EagerSingleton getInstance(){
return instance;
}
}
/**
* 线程不安全的饱汉式
*/
class LazySingleton{
private static LazySingleton instance;
private LazySingleton(){}
public LazySingleton getInstance(){
if(instance == null){
instance = new LazySingleton();
}
return instance;
}
}
/**
* 线程安全的饱汉式
* 即双重锁判定模式
*/
class LockSingleton{
private static LockSingleton instance;
private LockSingleton(){}
public LockSingleton getInstance(){
if (instance == null) {
synchronized (LockSingleton.class) {
if (instance == null) {
instance = new LockSingleton();
}
}
}
return instance;
}
}
/**
* 线程安全的单例模式二
*/
class SafeSingleton{
private static SafeSingleton instance;
private SafeSingleton(){}
public synchronized SafeSingleton getInstance(){
if(instance == null){
instance = new SafeSingleton();
}
return instance;
}
}
/**
* 只有一个枚举值的枚举也可以用作单例模式
*/
enum EnumSingleton{
INSTANCE {
@Override
protected void someMethod() {
// TODO Auto-generated method stub
//需要实现的代码
}
};
protected abstract void someMethod();
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2