美文网首页
java23种设计模式—— 二、单例模式

java23种设计模式—— 二、单例模式

作者: witmy | 来源:发表于2020-10-03 12:35 被阅读0次

源码在我的githubgitee中获取

介绍

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

注意:

  • 1、单例类只能有一个实例。

  • 2、单例类必须自己创建自己的唯一实例。

  • 3、单例类必须给所有其他对象提供这一实例。

实现方式

饿汉式单例(静态常量,线程安全)

顾名思义,饿汉式单例它很“饿”,所以一开始就创建了唯一但单例实例,但如果你没有使用过这个实例,就会造成内存的浪费


/**

* 饿汉式单例

* 优点:简单,在类装载时就完成了实例化,避免了线程同步问题,线程安全

* 缺点:由于这个类已经完成了实例化,如果从始至终都没有用过这个实例,就会造成内存的浪费

  */

public class SingletonTest01 {

    public static void main(String[] args) {

        Signleton instance1= Signleton.getInstance();

        Signleton instance2 = Signleton.getInstance();

        System.out.println(instance1==instance2);

        System.out.println(instance1.hashCode());

        System.out.println(instance2.hashCode());

    }

}

class Signleton{

    //1、构造器私有化,外部无法通过new新建

    private Signleton(){ }

    //2、内部创建对象实例

    private final static Signleton instance = new Signleton();

    //3、提供一个公有的静态方法,返回实例对象

    public final static Signleton getInstance(){

        return instance;

    }

}

输出结果


true

1163157884

1163157884

可以看到输出的是同一个实例

饿汉式单例(静态代码块,线程安全)

和之前的方式类似,只不过将类实例化的过程放在了静态代码块中,也就是类装载的时候,

就执行静态代码块中的代码,优缺点和之前一样


/**

* 和之前的方式类似,只不过将类实例化的过程放在了静态代码块中,也就是类装载的时候,

* 就执行静态代码块中的代码,优缺点和之前一样

*/

public class SingletonTest02 extends Thread{

    public static void main(String[] args) {

        Signleton instance1= Signleton.getInstance();

        Signleton instance2 = Signleton.getInstance();

        System.out.println(instance1==instance2);

        System.out.println(instance1.hashCode());

        System.out.println(instance2.hashCode());

    }

}

class Signleton{

    //1、构造器私有化,外部无法通过new新建

    private Signleton(){}

    //2、内部创建对象实例

    private static Signleton instance;

    static {//静态代码块种,创建单例对象

        instance = new Signleton();

    }

    //3、提供一个公有的静态方法,返回实例对象

    public final static Signleton getInstance(){

        return instance;

    }

}

输出


true

1163157884

1163157884

懒汉式(线程不安全)

同样,顾名思义,懒汉式单例它很懒。只有在你用到它时,它才会创建一个实例。


/**

* 饿汉式-线程不安全

* 优点:起到了懒加载的效果,但是只能在单线程下使用

* 如果在多线程下,如果一个线程进入了if判断语句块,

* 还没来得及向下执行,另一个线程也进入这个判断语句,就会产生多个实例(违背单例模式),

* 实际开发中,不要使用这种方式

*/

public class SingletonTest03 {

    public static void main(String[] args) {

        for (int i = 0; i <10 ; i++) {

            new Thread(() -> System.out.println(Signleton.getInstance().hashCode()) ).start();

        }

    }

}

class Signleton{

    private static Signleton instance;

    private Signleton(){}

    //提供一个静态的公有方法,当调用方法时,才去创建instance

    public static Signleton getInstance(){

        if(instance == null){//如果为空再去创建对象

            instance = new Signleton();

        }

        return instance;

    }

}

输出


546405844

135417039

135417039

802181073

135417039

135417039

135417039

802181073

135417039

135417039

这里我选了个比较极端的情况,如果你的电脑配置比较好,可能运行几次结果都是符合单例模式的。

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

上面方法之所以会存在线程不安全的情况,是因为多线程情况下,可能会有多条线程同时判断单例是否创建。那么要解决这个问题 ,只需要同步getInstance()方法


/**

* 解决了线程不安全的问题

* 但是大大降低了效率 每个线程想获得实例的时候,执行getInstance()方法都要进行同步

*/

public class SingletonTest04 {

    public static void main(String[] args) {

        for (int i = 0; i <10 ; i++) {

            new Thread(() -> System.out.println(Signleton.getInstance().hashCode()) ).start();

        }

    }

}

class Signleton{

    private static Signleton instance;

    private Signleton(){}

    //提供一个静态的公有方法,当调用方法时,才去创建instance

    public static synchronized Signleton getInstance(){

        if(instance == null){//如果为空再去创建对象

            instance = new Signleton();

        }

        return instance;

    }

}

结果


802181073

802181073

802181073

802181073

802181073

802181073

802181073

802181073

802181073

802181073

但是,synchronized是一个很重量的同步锁,而我们每次执行getInstance()时都会进行同步,极其影响效率

懒汉式(双重检查,线程安全)

双检锁,又叫双重校验锁,综合了懒汉式和饿汉式两者的优缺点整合而成。看上面代码实现中,特点是在synchronized关键字内外都加了一层 if 条件判断,这样既保证了线程安全,又比直接上锁提高了执行效率,还节省了内存空间


/**

* 懒汉模式-双重检查

* 进行了两次if判断检查,这样就保证线程安全了

* 通过判断是否为空,来确定是否 需要再次实例化

*/

public class SingletonTest05 {

    public static void main(String[] args) {

        for (int i = 0; i <10 ; i++) {

            new Thread(() -> System.out.println(Signleton.getInstance().hashCode()) ).start();

        }

    }

}

class Signleton{

    private static volatile Signleton instance;//volatile保证可见性

    private Signleton(){}

    //提供一个静态的公有方法,加入双重检查代码,解决线程安全问题,同时解决懒加载问题

    public static Signleton getInstance() {

        if (instance == null) {

            synchronized (Signleton.class) {

                if (instance == null) {

                    instance = new Signleton();

                }

            }

        }

        return instance;

    }

}

运行结果


79372097

79372097

79372097

79372097

79372097

79372097

79372097

79372097

79372097

79372097

推荐使用

静态内部类(线程安全)


/**

* 静态内部类实现单例模式

* 该方法采用了类装载机制来保证初始化实例时只有一个线程

* 静态内部类在Signleton类被装载时并不会立即实例化,而是需要实例化时,才会装载SignletonInstance类

* 类的静态属性只会在第一次加载类的时候初始化

* 避免了线程不安全,利用静态内部类实现懒加载,效率高

*/

public class SingletonTest07 {

    public static void main(String[] args) {

        for (int i = 0; i <10 ; i++) {

            new Thread(() -> System.out.println(Signleton.getInstance().hashCode()) ).start();

        }

    }

}

class Signleton{

    //构造器私有

    private Signleton(){}

    //静态内部类,该类中有一个静态属性Signleton

    private static class SignletonInstance{

        private static final Signleton instance = new Signleton();

    }

    //提供一个静态的公有方法,直接返回SignletonInstance.instance

    public static Signleton getInstance() {

        return SignletonInstance.instance;

    }

}

结果


79372097

79372097

79372097

79372097

79372097

79372097

79372097

79372097

79372097

79372097

这种方式较为简单,推荐使用

枚举(线程安全)


/**

* @author codermy

* @createTime 2020/5/14

* 枚举方法实现单例模式

* 借助jdk1.5中添加的枚举类来实现单例模式,

* 不仅能避免多线程同步问题,而且还能防止反序列化重新创建新对象

*/

public class SingletonTest08 {

    public static void main(String[] args) {

        Singleton singleton = Singleton.INSTANCE;

        singleton.Ok();

        for (int i = 0; i <10 ; i++) {

            new Thread(() -> System.out.println(Singleton.INSTANCE.hashCode()) ).start();

        }

    }

}

enum Singleton{

    INSTANCE;//属性

    public void Ok(){

        System.out.println("ok");

    }

}

结果


ok

858497792

858497792

858497792

858497792

858497792

858497792

858497792

858497792

858497792

858497792

可以看出,枚举实现单例模式,最为简洁,较为推荐。但是正是因为它简洁,导致可读性较差

相关文章

  • 单例模式

    JAVA设计模式之单例模式 十种常用的设计模式 概念: java中单例模式是一种常见的设计模式,单例模式的写法...

  • 23设计模式之一

    简述 一、设计模式的六大原则 二、23种设计模式 1.单例模式 懒汉式单例 饿汉单例 2.三种工厂模式 1>.简单...

  • java23种设计模式—— 二、单例模式

    源码在我的github[https://github.com/witmy/JavaDesignPattern]和g...

  • iOS-单例模式

    swift的单例设计模式 OC的单例设计模式 新学习一种单例思想

  • Go语言设计模式(1)单例模式

    Go语言设计模式(1)单例模式 单例模式的定义 个人认为单例模式是23种设计模式中最简单也最好理解的一种,定义如下...

  • 设计模式

    [TOC] #设计模式 --- ##单例模式 >[八种单例模式参考](http://cantellow.iteye...

  • 单例模式

    单例 单例模式,是一种设计模式,属于创建型设计模式,还有一种创建型设计模式,工厂模式。设计模式总共有23种,三大类...

  • JAVA多线程之线程安全的单例模式

    概念:java中单例模式是一种常见的设计模式,单例模式分三种:懒汉式单例、饿汉式单例、登记式单例三种。单例模式有一...

  • 单例模式

    概念 java中单例模式是一种常见的设计模式,单例模式分三种:懒汉式模式,饿汉式模式、登记式单例三种。单例模式有以...

  • 单例设计模式

    单例设计模式 单例设计模式介绍 单例设计模式的八种方法2.1 饿汉式(静态常量)2.1.1 实现步骤2.1.2 代...

网友评论

      本文标题:java23种设计模式—— 二、单例模式

      本文链接:https://www.haomeiwen.com/subject/abrwuktx.html