1、单例模式定义
确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
2、单例模式实现
public class Singleton {
/* The volatile keyword ensures that multiple threads
* handle the uniqueInstance variable correctly when it
* is being initialized to the Singleton instance.
* */
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;
}
}
3、单例模式特点
由于单例模式在内存中只有一个实例,减少了内存开销。 |
单例模式可以避免对资源的多重占用,例如一个写文件时,由于只有一个实例存在内存中,避免对同一个资源文件的同时写操作。 |
单例模式可以再系统设置全局的访问点,优化和共享资源访问。 |