设计模式--单例模式Singleton

单例设计模式

单例设计模式:采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的静态方法。

单例设计模式的八种方式:

  1. 饿汉式(静态常量)
  2. 饿汉式(静态代码块)
  3. 懒汉式(线程不安全)
  4. 懒汉式(线程安全,同步方法)
  5. 懒汉式(线程不安全,同步代码块)
  6. 双重检查
  7. 静态内部类
  8. 枚举

1. 饿汉式(静态常量)

“饿汉式” ,就是你可以试着想想一下,一个饿汉的行为,肯定是见到了食物就去吃。即无论是否需要实例对象,都会在内存中去自动加载一份。

优缺点说明:

  1. 优点:写法实现简单,在类装载的时候就完成了实例化。避免了线程同步的问题。
  2. 缺点:在类装载时完成实例化,若一直没有使用过这个实例,则会造成内存资源的浪费。

这种单例模式可以使用,可能会造成资源的浪费。

代码实现:

package com.robin.singleton.type1;

public class SingletonTest1 {
    public static void main(String[] args) {
        // 测试单例模式--饿汉式(静态常量)
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
        // instance1 与 instance2 哈希值一致,是同一个对象实例
    }
}

// 单例模式----饿汉式(静态常量)

class Singleton{
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton(){}

    // 类加载时,即创建唯一的一份对象
    private final static Singleton instance = new Singleton();

    // 对外提供一个公共的返回 singleton 实例对象
    public static Singleton getInstance(){
        return instance;
    }
}

2. 饿汉式(静态代码块)

与上面第一种方式类似,只不过是将类实例化的过程放到了静态代码块中,优缺点与上面一致。

代码实现:

package com.robin.singleton.type2;

public class SingletonTest2 {
    public static void main(String[] args) {
        // 测试单例模式--饿汉式(静态代码块)
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
        // instance1 与 instance2 哈希值一致,是同一个对象实例
    }
}

// 单例模式----饿汉式(静态代码块)

class Singleton{
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton(){}

    private static Singleton instance ;

    // 在静态代码块中-->类加载时,完成instance的初始化
    static {
        instance = new Singleton();
    }

    // 对外提供一个公共的返回 singleton 实例对象
    public static Singleton getInstance(){
        return instance;
    }
}

3. 懒汉式(线程不安全)

“懒汉式”,当饿极了才去吃东西。即当需要时,才将类实例对象创建并且加载到内存中。

优缺点:

  1. 实现了延迟加载,但只能在单线程下使用。
  2. 在多线程下,会产生多个实例。
  3. 实际开发中,不要使用这种方式。

代码实现:

package com.robin.singleton.type3;

public class SingletonTest3 {
    public static void main(String[] args) {
        // 测试单例模式--懒汉式(线程不安全)
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
        // instance1 与 instance2 哈希值一致,是同一个对象实例

    }

}

// 单例模式----饿汉式(静态代码块)

class Singleton {
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton() {
    }

    private static Singleton instance;


    // 当使用到时,才去初始化实例对象(懒汉式)
    // 对外提供一个公共的返回 singleton 实例对象
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

多线程测试:

package com.robin.singleton.type3.threadSingleton;

public class TestThreadSingleton {
    public static void main(String[] args) {
        System.out.println("~~~~~多线程测试~~~~~");
        // 多线程测试懒汉式的线程不安全的写法
        for (int i = 0; i < 100; i++) {
            // 匿名内部类+lambda表达式
            new Thread(() -> {
                System.out.println(Singleton.getInstance().hashCode());
            }).start();
        }
        // hashCode 都乱了。线程不安全
    }
}

// 懒汉式(线程不安全)
class Singleton{
    // 私有构造器
    private Singleton(){}

    private static Singleton instance;

    // 懒汉式,当需要时进行加载(调用getInstance()方法)获得实例对象
    // 提供对外公共的 getInstance()
    public static Singleton getInstance(){
        if (instance==null){
            // 线程睡眠1s进行测试
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            instance = new Singleton();
        }
        return instance;
    }
}

在这里插入图片描述

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

代码实现:

package com.robin.singleton.type4;

public class SingletonTest4 {
    public static void main(String[] args) {
        // 测试单例模式--懒汉式(线程安全)
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
        // instance1 与 instance2 哈希值一致,是同一个对象实例
    }
}

// 单例模式----懒汉式(线程安全)
class Singleton{
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton(){}

    private static Singleton instance ;

    // 对外提供一个公共的返回 singleton 实例对象的方法getInstance()
    // 使用同步方法 synchronized 线程同步锁
    public static synchronized Singleton getInstance(){
        if (instance==null){
            instance = new Singleton();
        }
        return instance;
    }
}

线程测试:

package com.robin.singleton.type4.threadSingleton;

public class TestThreadSingleton {
    public static void main(String[] args) {
        System.out.println("多线程测试【懒汉式单例模式】");
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                System.out.println(Singleton.getInstance().hashCode());
            }).start();
        }
        // 哈希值没有乱,线程安全
        // 但是同步锁 synchronized 比较耗费时间,效率不高
    }
}

// 懒汉式(线程安全)
class Singleton{

    // 私有化构造器
    private Singleton(){}
    // 静态变量
    private static Singleton instance;
    // 向外提供getInstance()方法,需要时才创建
    // synchronized 线程同步锁
    public static synchronized Singleton getInstance(){
        if (instance==null){
            // 为了线程测试,线程中断休眠1s
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            instance = new Singleton();
        }
        return instance;
    }
}

在这里插入图片描述

优缺点:

  1. 优点:通过synchronized同步方法解决了多线程的安全问题
  2. 缺点:效率较低,因为同步锁的问题,内次都需要进行锁,无论实例是否存在

实际开发中,不推荐这种使用方式。

5. 懒汉式(线程不安全,同步代码块)

代码实现:

package com.robin.singleton.type5;

public class SingletonTest5 {
    public static void main(String[] args) {
        // 测试单例模式--懒汉式(线程不安全)
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
        // instance1 与 instance2 哈希值一致,是同一个对象实例
    }
}

// 单例模式----懒汉式(线程不安全,妄图通过减小同步代码块的方式来提高效率)
class Singleton{
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton(){}

    private static Singleton instance ;

    // 对外提供一个公共的返回 singleton 实例对象的方法getInstance()
    public static  Singleton getInstance(){
        if (instance==null){
            // 妄图通过减小同步代码块的方式来提高效率,会导致线程不安全
            synchronized(Singleton.class){
                instance = new Singleton();
            }
        }
        return instance;
    }
}

多线程测试:

package com.robin.singleton.type5.threadSingleton;

public class SingletonTest5 {
    public static void main(String[] args) {
        // 测试单例模式--懒汉式(线程不安全)
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                System.out.println(Singleton.getInstance().hashCode());
            }).start();
        }
    }
}

// 单例模式----懒汉式(线程不安全,妄图通过减小同步代码块的方式来提高效率)
class Singleton{
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton(){}

    private static Singleton instance ;

    // 对外提供一个公共的返回 singleton 实例对象的方法getInstance()
    public static  Singleton getInstance(){
        if (instance==null){
            // 妄图通过减小同步代码块的方式来提高效率,会导致线程不安全
            synchronized(Singleton.class){
                // 线程休眠1s
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                instance = new Singleton();
            }

        }
        return instance;
    }
}

在这里插入图片描述

妄图通过减小同步代码块的方式来提高效率,但会导致多线程还是存在安全问题,只能在单线程下使用,不推荐使用。

6. 双重检查

通过双重检查保证线程安全,两次 if(singleton==null)。实例化代码只执行一次,避免反复进行方法同步。

代码实现:

package com.robin.singleton.type6;

public class SingletonTest6 {
    public static void main(String[] args) {
        // 测试单例模式--双重检查
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
    }
}

// 单例模式--双重检查
class Singleton{
    private Singleton(){};

    // 使用 volatile 关键字
    private static volatile Singleton instance;

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

}

解决了多线程的安全问题,双重检查可以解决懒加载问题,即在使用时才会加载(避免浪费内存资源),同时保证了效率,推荐使用。

7. 静态内部类

静态内部类在使用时才会实例化,避免资源浪费,实现延迟加载。同时JVM保证了线程的安全,在类进行初始化时,只有一个线程才能进入。

代码实现:

package com.robin.singleton.type7;

public class SingletonTest7 {
    public static void main(String[] args) {
        // 测试单例模式--静态内部类的方式
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
    }
}

// 单例模式--静态内部类的方式
class Singleton{
    private Singleton(){};

    // 私有静态内部类
    private static class SingletonInstance{
        private static final Singleton INSTANCE =new Singleton();
    }

    // 提供公有的外部获取实例的方法 getInstance()
    public static Singleton getInstance(){
        return SingletonInstance.INSTANCE;
    }

}

避免了线程不安全,利用静态内部类的特点实现延迟加载,效率高。

推荐使用+1!

8. 枚举

使用枚举来实现单例模式,既可以避免多线程同步问题,也能防止反序列化重新创建新的对象。推荐使用+1!

代码实现:

package com.robin.singleton.type8;

public class SingletonTest8 {
    public static void main(String[] args) {
        // 测试单例模式--枚举的方式
        Singleton instance1 = Singleton.INSTANCE;
        Singleton instance2 = Singleton.INSTANCE;
        System.out.println(instance1==instance2);
        System.out.println("instance1===="+instance1.hashCode());
        System.out.println("instance2===="+instance2.hashCode());
    }
}

// 单例模式--枚举的方式
enum Singleton{
    INSTANCE;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杀死一只知更鸟debug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值