饿汉式单例:
public class Singleton {
private Singleton(){}
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
懒汉式单例:
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static synchronized Singleton getInstance(){
if (instance == null)
instance = new Singleton();
return instance;
}
}
实现一个单例有两点注意事项:
- 将构造器私有,不允许外界通过构造器创建对象
- 通过公开的静态方法向外界返回类的唯一实例