概念
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
代码
饥汉模式
public class SingletonHungry {
private static SingletonHungry singletonHungry = new SingletonHungry();
public static SingletonHungry getInstance(){
return singletonHungry;
}
}
懒汉模式
public class SingletonLazy {
private static SingletonLazy singletonLazy = null;
public static SingletonLazy getInstance(){
if (singletonLazy == null) {
synchronized (SingletonLazy.class) {
if (singletonLazy == null) {
singletonLazy = new SingletonLazy();
}
}
}
return singletonLazy;
}
}