单例的几种写法

来源:互联网 发布:贪心算法 最优合并 编辑:程序博客网 时间:2024/06/01 21:25

单例模式的运用十分广泛,下面给出单例模式的几种写法

1.懒汉

懒汉就意味着只在需要的时候才进行初始化,但是线程不安全

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

2.线程安全的懒汉

线程安全,但是效率低,毕竟进行一次初始化以后的同步锁定毫无意义。

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

3.饿汉

饿汉在类加载的时候就会对static的instance完成初始化

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

4.双重检验锁

两次校验,第二次加锁,可以避免初始化后同步效率低的问题。

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

单例模式的七种写法:http://cantellow.iteye.com/blog/838473

0 0
原创粉丝点击