设计模式之:单例模式

译林 / 2023-08-09 / 原文

实现单例模式的8种方式

  • 饿汉式(静态常量)
  • 饿汉式(静态代码块)
  • 懒汉式(线程不安全)
  • 懒汉式(线程安全,同步方法)
  • 懒汉式(线程安全,同步代码块)
  • 双重检查(推荐使用)
  • 静态的内部类(推荐使用)
  • 枚举(推荐使用)

实际使用场景

jdk中的RunTime

饿汉式(静态常量)

/**
 * @description: 单利模式:饿汉式(静态常量)
 * @author: abel.he
 * @date: 2023-08-09
 **/
public class Singleton {

    public static void main(String[] args) {
        SingletonPattern instance1 = SingletonPattern.getInstance();
        SingletonPattern instance2 = SingletonPattern.getInstance();
        System.out.println(instance2 == instance1);

        System.out.println("instance1.hashCode:" + instance1.hashCode());
        System.out.println("instance2.hashCode:" + instance2.hashCode());

    }

}

class SingletonPattern {
    private SingletonPattern() {

    }

    private static final SingletonPattern singletonPattern = new SingletonPattern();

    public static SingletonPattern getInstance() {
        return singletonPattern;
    }

}

优缺点说明:

  • 优点:这种写法比较简单,类装在的时候完成实例化。避免线程同步问题。
  • 缺点:在类装载的时候完成实例化,没有达到Lazy Loading的效果,没有使用过这个实例,会造成内存的浪费
  • 结论:这种单例模式可用,可能造成内存浪费

饿汉式(静态代码块)

/**
 * @description: 单例模式:饿汉式(静态代码块)
 * @author: abel.he
 * @date: 2023-08-09
 **/
public class Singleton {

    public static void main(String[] args) {
        SingletonPattern instance1 = SingletonPattern.getInstance();
        SingletonPattern instance2 = SingletonPattern.getInstance();
        System.out.println(instance2 == instance1);

        System.out.println("instance1.hashCode:" + instance1.hashCode());
        System.out.println("instance2.hashCode:" + instance2.hashCode());

    }

}

class SingletonPattern {
    private SingletonPattern() {

    }

    private static SingletonPattern singletonPattern;

    static {
        singletonPattern = new SingletonPattern();
    }

    public static SingletonPattern getInstance() {
        return singletonPattern;
    }
}

优缺点说明:

  • 优点:这种写法比较简单,类装在的时候完成实例化。避免线程同步问题。
  • 缺点:在类装载的时候完成实例化,没有达到Lazy Loading的效果,没有使用过这个实例,会造成内存的浪费
  • 结论:这种单例模式可用,可能造成内存浪费

懒汉式(线程不安全)

 

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

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

双重检查(推荐使用)

静态的内部类(推荐使用)

枚举(推荐使用)