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

源码在个人githubgitee中获取java

介绍

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于建立型模式,它提供了一种建立对象的最佳方式。
这种模式涉及到一个单一的类,该类负责建立本身的对象,同时确保只有单个对象被建立。这个类提供了一种访问其惟一的对象的方式,能够直接访问,不须要实例化该类的对象。
注意:git

  • 一、单例类只能有一个实例。
  • 二、单例类必须本身建立本身的惟一实例。
  • 三、单例类必须给全部其余对象提供这一实例。

实现方式

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

顾名思义,饿汉式单例它很“饿”,因此一开始就建立了惟一但单例实例,但若是你没有使用过这个实例,就会形成内存的浪费github

/**
* 饿汉式单例
 * 优势:简单,在类装载时就完成了实例化,避免了线程同步问题,线程安全
 * 缺点:因为这个类已经完成了实例化,若是从始至终都没有用过这个实例,就会形成内存的浪费
  */
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{
    //一、构造器私有化,外部没法经过new新建
    private Signleton(){ }
    //二、内部建立对象实例
    private final static Signleton instance = new Signleton();
    //三、提供一个公有的静态方法,返回实例对象
    public final static Signleton getInstance(){
        return instance;
    }
}

输出结果设计模式

true
1163157884
1163157884

能够看到输出的是同一个实例安全

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

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

就执行静态代码块中的代码,优缺点和以前同样多线程

/**
 * 和以前的方式相似,只不过将类实例化的过程放在了静态代码块中,也就是类装载的时候,
 * 就执行静态代码块中的代码,优缺点和以前同样
 */
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{
    //一、构造器私有化,外部没法经过new新建
    private Signleton(){}
    //二、内部建立对象实例
    private static Signleton instance;

    static {//静态代码块种,建立单例对象
        instance = new Signleton();
    }
    //三、提供一个公有的静态方法,返回实例对象
    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;
    }
}

输出code

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

能够看出,枚举实现单例模式,最为简洁,较为推荐。可是正是由于它简洁,致使可读性较差

相关文章
相关标签/搜索