(2)Java设计模式之——单例模式

单例模式是java的常用设计模式之一,它属于创建型模式。

它可以保证一个类只有一个实例,并提供一个全局的访问点,当你想控制实例数目,节约系统资源的时候可以使用。

单例模式主要分为懒汉式和饿汉式,下面举例说明:

 

1、懒汉式,非线程安全

/**
 * 懒汉式单例类
 */
public class Singleton {
    private Singleton(){}
    private static Singleton singleton = null;

    public static Singleton getSingleton(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}

以上方法的懒汉式单例并没有考虑线程安全,如果在并发环境下其实是会出现多个singleton的实例。

下面我们来看看让它实现线程安全的几种方式。

2、懒汉式,线程安全

增加关键字synchronized实现线程安全

/**
 * 懒汉式单例类
 */
public class Singleton {
    private Singleton(){}
    private static Singleton singleton = null;

    public static synchronized Singleton getSingleton(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}

 

双重检查锁定,实现线程安全

/**
 * 懒汉式单例类
 */
public class Singleton {
    private Singleton(){}
    private static Singleton singleton = null;

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

 

静态内部类,实现线程安全

/**
 * 懒汉式单例类
 */
public class Singleton {
    private Singleton(){}
    private static Singleton singleton = null;

    private static class lazy{
        private static final Singleton SINGLETON = new Singleton();
    }
    public static final Singleton getSingleton(){
        return lazy.SINGLETON;
    }
}

以上三种方式,在懒汉模式下实现线程安全,很明显第三种方式要比前两种好。

 

3、饿汉式

/**
 * 饿汉式单例类
 */
public class Singleton2 {
    private Singleton2(){}
    private static Singleton2 SINGLETON_2 = new Singleton2();

    public static Singleton2 getSingleton2(){
        return SINGLETON_2;
    }
}

饿汉式在类加载时就生成了一个静态的对象供系统使用,也不会再改变了,所以它是线程安全的。

 

总结:

懒汉式和饿汉式的区别:

1、懒汉式是在第一次调用时才会去实例化,而饿汉式是在类加载时就会实例化这个单例。

      也就是说懒汉式在第一次使用时,相比于饿汉式会有一定的延迟因为需要去实例化,而饿汉式却不会有这个问题。

      饿汉式在类创建时就会实例化静态对象,无论后面是否用得到都会占用一定的资源。

2、懒汉式是有一定线程问题的,如果需要线程安全并不能直接使用,而饿汉式是天生就线程安全的无需处理。

 

posted @ 2021-01-29 23:20  每天努力一小步  阅读(81)  评论(0)    收藏  举报