单件模式就是要保证一个类只有一个实例。
//第一种形式,饿汉式:
public class Singleton {
//private 类型的静态变量
private static Singleton instance = new Singleton();
//构造函数为private类型
private Singleton() {
}
//public 类型的getInstance()方法,
public static Singleton getInstance() {
return instance;
}
}
//第二种形式,懒汉式:
public class Singleton {
private static Singleton instance = null;
public static synchronized Singletion getInstance() {
if (instance == null) {
instance = new Singletion();
return instance;
}
}
}