java设计模式(一)创建型模式之 单例模式(饿汉式,懒汉式,线程安全,双重检查)

1.介绍

    单例模式是一种常用的软件设计模式,其定义是单例对象的类只能允许一个实例存在。 

2.实现思路与步骤

  1).将该类的构造方法定义为私有方法,这样其他处的代码就无法通过调用该类的构造方法来实例化该类的对象,只有通过该类提供的静态方法来得到该类的唯一实例;

  2).在该类内提供一个静态方法,当我们调用这个方法时,如果类持有的引用不为空就返回这个引用,如果类保持的引用为空就创建该类的实例并将实例的引用赋予该类保持的引用。

2.单例模式实现

   1)、饿汉式  

public class Singleton {

    private final static Singleton instance= new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return instance;
    }
}

 优点:这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。

 缺点:在类装载的时候就完成实例化,没有达到延迟加载的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费。

 2)、懒汉式

public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

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

优点:这种写法起到了延迟加载的效果,仅适合于单线程环境

缺点: 如果在多线程下,一个线程进入了if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例

3)、懒汉式(线程安全,同步方法)

public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

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

优点:解决了线程不安全的问题

缺点: 效率低,每个线程都要执行getInstance()方法进行同步。而其实这个方法只执行一次实例化代码就够了,后面的想获得该类的实例,直接return就行了

5) 双重检查

public class Singleton {

    private static volatile Singleton singleton;

    private Singleton() {}

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

       双重检测概念对于多线程开发者来说不会陌生,如代码中所示,我们进行了两次if (singleton == null)检查,这样就可以保证线程安全了。这样,实例化代码只用执行一次,后面再次访问时,判断if (singleton == null),直接return实例化对象。

优点:线程安全;延迟加载;效率较高。

猜你喜欢

转载自blog.csdn.net/weixin_43870026/article/details/85236986