单例模式的讨论
来源:互联网 发布:汽车租赁软件 编辑:程序博客网 时间:2024/05/21 21:36
单例相对于静态变量的优势:
(1),可以支持延迟加载
(2),可以支持多态
最简单的单例模式
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance(){
return instance;
}
}
缺点:一开始就初始化,有可能浪费资源
有可能一开始的时候初始化所需的信息不足
为避免浪费资源,使用延迟加载:
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
好处:用到的时候才初始化,避免浪费。
缺点:非线程安全,多线程环境下有可能产生多个实例
解决线程安全性:
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
缺点:资源消耗比较大
有可能引入空指针
可以使用静态内部类来实现单例的延迟夹杂,
public class Foo {
private static class LazyFoo {
public static Foo foo = new Foo();
}
public static Foo getInstance() {
return LazyFoo.foo;
}
}
静态内部类, 只有当有引用时, 内部类才会被装载,从而实现延迟加载
当需求是需要该类有唯一实例,但该类的初始化需要外部信息
public class Singleton {
private static Singleton instance = null;
private static A iA = null;
private Singleton(A a) {
iA = a;
}
public static Singleton getInstance(A a){
if(instance == null){
instance = new Singleton(a);
}
return instance;
}
}
缺点:所有使用该实例的对象都被要求知道A
或者:
public class Singleton {
private static Singleton instance = null;
private static A iA = null;
private Singleton() {
}
public static Singleton getInstance(A a){
if(instance == null){
instance = new Singleton();
}
return instance;
}
public static void setA(A a){
iA = a;
}
}
缺点:获得该实例之前必须设置相关的外部信息
单例模式相对于静态变量来说有支持子类化的优势
由外部信息获取单例的子类:
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance(int aParam){
if(instance == null){
if(aParam == 0){
instance = new SubSingleton1();
}else if(aParam == 1){
instance = new SubSingleton2();
}
else{
instance = new Singleton();
}
}
return instance;
}
}
- 单例模式的讨论
- 单例模式的深入讨论
- java单例模式的讨论
- python的单例模式与讨论
- 单例模式的写法和线程安全性的讨论
- 可能是最全的Java单例模式讨论
- 关于单例模式的一些讨论(实现单例模式)
- 单例的扩展性讨论
- 单例模式再讨论(有关序列化的单例问题)
- 单例模式再讨论(有关序列化的单例问题)
- 单例模式(3)- 饿汉式单例与懒汉式单例的讨论
- 单例与static的一些讨论
- java设计模式-单例模式讨论篇:单例模式与垃圾回收
- 单例模式讨论篇:单例模式与垃圾回收
- 单例模式讨论篇:单例模式与垃圾回收
- 单例模式讨论篇:单例模式与垃圾回收
- 单例模式讨论篇:单例模式与垃圾回收
- 单例模式讨论篇:单例模式与垃圾回收
- 注解与反射
- Hibernate與MySQL開發中亂碼解決方案 .
- 串行通信类CSerial简介
- 双节主要公交延点半小时 城南客运站网上售票
- 手机安卓刷机包自己做 ---- 电脑报37期
- 单例模式的讨论
- c primer plus 第六章 13
- 如何战胜拖延的毛病
- 前世今生
- OLAP中的统计分析:切片 切块 钻取 旋转
- 关于对SD模块的理解
- Ajax解析XML
- fork vfork .
- HDU 3874 Necklace 树状数组的应用