Last active
July 11, 2023 06:20
-
-
Save AutMaple/ca200e45dafa6f6d71158b65dd418660 to your computer and use it in GitHub Desktop.
[单例模式] #设计模式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 饿汉式单例模式,并发安全,但是会浪费系统资源。 | |
| public class EagerSingleton { | |
| private static EagerSingleton instance = new EagerSingleton(); | |
| private EagerSingleton(){} | |
| public static EagerSingleton getInstance(){ | |
| return instance; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 懒汉式单例模式,并发安全,但是性能会有一些影响 | |
| 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; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 完美的单例实现模式,并发安全并性能良好,同时只有在需要的时候才会实例化对象,由虚拟机来保证线程安全性 | |
| // 利用的是类的加载机制:类只有在需要的时候才会被加载,即使是内部类。 | |
| // 下面的这种方式称为: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