Singleton单例模式

1.饿汉式
饿汉式就是在第一次引用该类的时候就创建对象实例,而不管是否 需要创建.
public class Singleton{
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance(){
return instance;
}
}
2.懒汉式
public class Singleton{
private static Singleton instance;
private Singleton(){}
private static Singleton getInstance(){
if(instance == null){
instance = new Singleton;
}
return instance;
}
}

你可能感兴趣的:(Singleton单例模式)