//饿汉单例,不适合大对象构建,适合小对象频繁用,用了这个类就会加载类的单例
class Singleton01{
private Singleton01(){}
private static Singleton01 instance =new Singleton01();
public static Singleton01 getInstance(){
return instance;
}
static void s(){};
}
//懒汉单例,适合大对象,稀少用
class Singleton02{
private Singleton02(){}
private static Singleton02 instance;
public static Singleton02 getInstance (){
if(instance==null){
synchronized (Singleton02.class) {
if(instance==null){
instance=new Singleton02();
}
}
}
return instance;
}}
//改进单例
class Singleton03{
private Singleton03(){}
private static class InnerSingle{
public static Singleton03 instance=new Singleton03();
}
//懒加载,利用了内部类的特点使用时才加载,何时使用何时加载,不用不加载
public static Singleton03 getInstance(){
return InnerSingle.instance;
}
}
//枚举单例,调用show方法 Singleton04.instance.show()实现单例
enum Singleton04{
INSTANCE;//枚举类的对象
public void show(){
System.out.println("show()");
}
}