使用单态模式的一个必要条件是:
在系统中要求一个类只有一个实例时才使用,它必须自行创造这个实例,
必须自行向系统提供这个实例。好处在于节省系统资源,保证系统访问的一致性。
1 – Eager Singleton:
class EagerSingleton
{
private EagerSingleton(){}//私有的构造函数,保证外部不可访问
private static EagerSingleton instance = new EagerSingleton();
public static EagerSingleton getInstance(){
return instance;
}
}
public class Test
{
public static void main(String args[]){
EagerSingleton e = EagerSingleton.getInstance();
}
}
2 – Lazy Singleton:
class LazySingleton
{
private static LazySingleton instance = null;
private LazySingleton(){}//私有的构造函数,保证外部不可访问
public synchronized static LazySingleton getInstance(){
if (instance == null){
instance = new LazySingleton();
}
return instance;
}
}
public class Test
{
public static void main(String args[]){
LazySingleton e = LazySingleton.getInstance();
}
}