单例Singleton

来源:互联网 发布:网站数据库是干嘛的 编辑:程序博客网 时间:2024/05/18 20:07

//恶汉式,可以在多线程环境下使用。但是会过早地创建实例,从而减低内存的使用效率

class Solution {    /**     * @return: The same instance of this class every time     */    private Solution(){};    public static Solution instance = new Solution();    public static Solution getInstance() {        // write your code here        return instance;    }};


//懒汉式,只能在单线程环境下使用。
class Solution {    /**     * @return: The same instance of this class every time     */    private Solution(){};    private static Solution instance = null;    public static Solution getInstance() {        // write your code here        if(instance == null){            instance = new Solution();        }        return instance;    }};

//懒汉式改进1。在getInstance方法上加同步。每次通过属性Instance得到单例都会去同步。而同步非常耗时。

class Solution {    /**     * @return: The same instance of this class every time     */    private Solution(){};    private static Solution instance = null;    public static synchronized Solution getInstance() {        // write your code here        if(instance == null){            instance = new Solution();        }        return instance;    }};


//懒汉式改进2。双重检查锁定。只需要在单例还没有被创建之前加锁。如果实例已经创建,则不需要进行加锁同步。

class Solution {    /**     * @return: The same instance of this class every time     */    private Solution(){};    private static Solution instance = null;    public static Solution getInstance() {        // write your code here        if(instance == null){            synchronized(Solution.class){                if(instance == null){                    instance = new Solution();                }            }        }        return instance;    }};




0 0
原创粉丝点击