您的位置:首页 > 其它

Singleton Pattern 单例模式

2015-07-05 04:39 260 查看
Singleton Pattern: ensures a class has only one instance, and provides a global point of access to it.

Note: carefully deal with multithreading.

Synchronizing a method can decrease performance by a factor of 100.

1. Synchronize method

public class Singleton {
private static Singleton uniqueInstance;
private Singleton(){}
public static synchronized Singleton getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}This has overhead. Lazy create. Only create instance when needed.
2. Eagerly create instance.

public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton(){}
public static Singleton getInstance() {
return uniqueInstance;
}
}
Eager create. Create an instance even it is not used.

3. Use double-checking locking
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance() {
if(uniqueInstance == null) {
synchronized(Singleton.class) {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
This reduce the synchronize overhead. Use volatile to ensure no cached variable.

应用:设备驱动
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: