什么是单例设计模式,有哪些例子
1.饿汉:如果应用程序总是创建并使用单例实例或在创建和运行时开销不大
class Single {
private Single(){}
private static Single single= new Single();
public static Single getInstance(){
return single;
}
}
2.懒汉:如果开销比较大,希望用到时才创建就要考虑延迟实例化 Singleton的初始化需要某些外部资源(比如网络或存储设备)
class Single {
private Single(){}
private static Single single= null;
public static Single getInstance(){
if ( single == null ) {
synchronized (Single.class) {
if ( single == null ) {
single = new Single();
}
}
}return single;
}
}
3.静态内部类
class Single {
private Single(){}
private static class SingleHandler{
private static Single single = new Single();
}
public static Single getInstance(){
return Single.SingleHandler.single;
}
}
4.枚举
public class Single {
private Single(){}
public enum SingleEnum {
singleHandler;
private Single single;
private SingleEnum () {
single = new Single();
}
public Single getSingle() {
return single;
}
}
public static Single getInstacne() {
return SingleEnum.singleHandler.getSingle();
}
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。