单例模式就是确保一个类只有一个实体,并且该实例心须自动创建,并向整个系统提供该实例.
下面是两个例子,饿汉式单例模式与懒汉式单例模式:
public class Singleton1 {
private static Singleton1 instance = new Singleton1();
protected Singleton1() {
}
public static Singleton1 getInstance(){
return instance;
}
}
public class Singleton2 {
private static Singleton2 instance = null;
protected Singleton2(){}
public static synchronized Singleton2 getInstance() {
if(instance == null){
instance = new Singleton2();
}
return instance;
}
}