剑指offer2:实现Singleton模式

来源:互联网 发布:天津基础教育网络平台 编辑:程序博客网 时间:2024/04/30 08:07

题目:设计一个类,我们只能生成该类的一个实例。


单例模式特点:
1 构造方法私有化
2 静态属性指向实例
3 getInstance返回实例

饿汉模式

public class Singleton {    private Singleton(){    }    private static Singleton instance = new Singleton();    public static Singleton getInstance(){        return instance;    }}

懒汉模式

public class Singleton {    private Singleton(){    }    private static Singleton instance = null;    public static Singleton getInstance(){        if(instance == null){            instance = new Singleton();        }        return instance;    }}

考虑线程安全

1 getInstance方法上加同步

public class Singleton {    private Singleton(){    }    private static Singleton instance = null;    public static synchronized Singleton getInstance(){        if(instance == null){            instance = new Singleton();        }        return instance;    }}

2 双重检查锁定

public class Singleton {    private Singleton(){    }    private static Singleton instance = null;    public static Singleton getInstance(){        if(instance == null){            synchronized(Singleton.class){                if(instance == null){                    instance = new Singleton();                }            }        }        return instance;    }}

需要注意的是,加锁非常耗时!!这两种方法因为线程同步,性能受到了影响。

更好的方法

Java中静态内部类可以访问其外部类的成员属性和方法,同时,静态内部类只有当被调用的时候才开始首次被加载

/** * 改进懒汉式--利用静态内部类实现外部类的单例 * @author lizhongping * */public class Singleton {    private Singleton(){    }    private static class SingletonBuilder{        private static Singleton instance =  new Singleton();    }    public static Singleton getInstance(){        return SingletonBuilder.instance;    }}
0 0
原创粉丝点击