单例模式
###1.单例模式
public class Singleton {
private static Singleton singleton;
public Singleton() {
}
public static Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
###2.懒汉写法
懒汉式就是什么时候调用什么时候就加载,需要时创建
public class LazySingle {
private static LazySingle lazySingle;
private LazySingle() {
}
public static synchronized LazySingle getInstance(){
if(lazySingle == null){
lazySingle = new LazySingle();
}
return lazySingle;
}
}
###3.饿汉写法
饿汉式就是不管用不用,类加载时就创建出来
public class EagerSingleton {
private static EagerSingleton eagerSingleton = new EagerSingleton();
private EagerSingleton(){
}
public static EagerSingleton getInstance(){
return eagerSingleton;
}
}