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

源码在我的githubgitee中获取

目录

java23种设计模式—— 一、设计模式介绍
java23种设计模式—— 二、单例模式
java23种设计模式——三、工厂模式
java23种设计模式——四、原型模式
java23种设计模式——五、建造者模式
java23种设计模式——六、适配器模式
java23种设计模式——七、桥接模式
java23种设计模式——八、组合模式

介绍

单例模式(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

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

posted @ 2020-08-26 17:26  codermy  阅读(757)  评论(0编辑  收藏  举报