单例模式可以提供该类唯一的一个实例化对象,适用于只需要一个该类对象的情况,主要有两种实现方式:
1、懒汉式:
public static class Singleton {
private static final Singleton INSTANCE = new Singleton();
public static Singleton getInstance() {
return INSTANCE;
}
private Singleton() {
}
}
2、饿汉式:
public static class Singleton {
private static Singleton INSTANCE = null;
public static Singleton getInstance() {
if(INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
}
private Singleton() {
}
}