来到黑马学习已经快四个月了,在这里每天都过得很充实,早上睁开眼就是敲代码,晚上睡觉闭上眼脑子里还是只有代码·····
今天和大家分享一下单例模式的几个小demo
1、懒汉写法,常用写法 | class LazySingleton{
private static LazySingleton singleton;
private LazySingleton(){
}
public static LazySingleton getInstance(){
if(singleton==null){
singleton=new LazySingleton();
}
return singleton;
}
}
|
2、恶汉写法,缺点是没有达到lazy loading的效果 | class HungrySingleton{
private static HungrySingleton singleton=new HungrySingleton();
private HungrySingleton(){}
public static HungrySingleton getInstance(){
return singleton;
}
}
|
3、静态内部类,优点:加载时不会初始化静态变量INSTANCE,因为没有主动使用,达到Lazy loading | class InternalSingleton{
private static class SingletonHolder{
private final static InternalSingleton INSTANCE=new InternalSingleton();
}
private InternalSingleton(){}
public static InternalSingleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
|
|