Skip to content

Instantly share code, notes, and snippets.

@AutMaple
Last active July 11, 2023 06:20
Show Gist options
  • Select an option

  • Save AutMaple/ca200e45dafa6f6d71158b65dd418660 to your computer and use it in GitHub Desktop.

Select an option

Save AutMaple/ca200e45dafa6f6d71158b65dd418660 to your computer and use it in GitHub Desktop.
[单例模式] #设计模式
// 饿汉式单例模式,并发安全,但是会浪费系统资源。
public class EagerSingleton {
private static EagerSingleton instance = new EagerSingleton();
private EagerSingleton(){}
public static EagerSingleton getInstance(){
return instance;
}
}
// 懒汉式单例模式,并发安全,但是性能会有一些影响
public class LazySingleton {
private static volatile LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if(instance == null) {
synchronized(LazySingleton.class) {
if(instance == null) {
instance = new LazySingleton();
}
}
}
return instance;
}
}
// 完美的单例实现模式,并发安全并性能良好,同时只有在需要的时候才会实例化对象,由虚拟机来保证线程安全性
// 利用的是类的加载机制:类只有在需要的时候才会被加载,即使是内部类。
// 下面的这种方式称为:Initialization on Demand Holder。该种方式利用了虚拟机的类加载机制,因此在大多数编程语言中并不适用
public class Singleton {
private static Singleton instance;
private Singleton() {}
private static class Holder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return Holder.instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment