Java单例模式-23种设计模式-Java基础学习(二十二)

 

Singleton是一种创建型模式,指某个类采用Singleton模式,则在这个类被创建后,只可能产生一个实

例供外部访问,并且提供一个全局的访问点。

 

设计步骤

1.私有化需要用单例模式的类的构造器

2.在其内部产生该类的实例化对象,并将其封装成private static类型。

3.定义一个公开的静态方法返回该类的实例。

 

懒汉式(非线程安全)

  1. public class Singleton {
  2.     private static Singleton instance;
  3.     private Singleton (){}
  4.     public static Singleton getInstance() {
  5.     if (instance == null) {
  6.         instance = new Singleton();
  7.     }
  8.     return instance;
  9.     }
  10. }

懒汉式(线程安全)

  1. public class Singleton {
  2.     private static Singleton instance;
  3.     private Singleton (){}
  4.     public static synchronized Singleton getInstance() {
  5.     if (instance == null) {
  6.         instance = new Singleton();
  7.     }
  8.     return instance;
  9.     }
  10. }

饿汉式(线程安全)

  1. public class Singleton {
  2.     private static Singleton instance = new Singleton();
  3.     private Singleton (){}
  4.     public static Singleton getInstance() {
  5.     return instance;
  6.     }
  7. }

饿汉式另一种实现方式(线程安全)

  1. public class Singleton {
  2.     private Singleton instance = null;
  3.     static {
  4.     instance = new Singleton();
  5.     }
  6.     private Singleton (){}
  7.     public static Singleton getInstance() {
  8.     return this.instance;
  9.     }
  10. }

静态内部类实现单例模式

  1. public class Singleton {
  2.     private static class SingletonHolder {
  3.     private static final Singleton INSTANCE = new Singleton();
  4.     }
  5.     private Singleton (){}
  6.     public static final Singleton getInstance() {
  7.     return SingletonHolder.INSTANCE;
  8.     }
  9. }

运用枚举实现单例模式

  1. public enum Singleton {
  2.     INSTANCE;
  3.     public void whateverMethod() {
  4.     }
  5. }

双重锁定实现单例模式

  1. public class Singleton {
  2.     private volatile static Singleton singleton;
  3.     private Singleton (){}
  4.     public static Singleton getSingleton() {
  5.     if (singleton == null) {
  6.         synchronized (Singleton.class) {
  7.         if (singleton == null) {
  8.             singleton = new Singleton();
  9.         }
  10.         }
  11.     }
  12.     return singleton;
  13.     }
  14. }

以上就是DannyWu给大家讲解的Java中单例模式,如有问题请在下方评论出提出,我们一同讨论!

weinxin
我的微信
有问题微信找我
DannyWu

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

Protected with IP Blacklist CloudIP Blacklist Cloud