如何通过Java代码解析实现单例设计模式的方法?

2026-05-26 07:051阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计565个文字,预计阅读时间需要3分钟。

如何通过Java代码解析实现单例设计模式的方法?

单例模式的几种实现方式:

1.饥汉式单例

方式一:枚举法获得单例对象 方式二:静态属性获得单例对象 方式三:静态方法获得单例对象

2.懒汉式单例

方式一:静态方法获得单例对象

单例模式的几种实现方式:

一:饿汉式单例

方式一:枚举方式获得单例对象

方式二:静态属性获得单例对象

方式三:静态方法获得单例对象

二:懒汉式单例

方式一:静态方法获得单例对象(线程安全)

方式二:内部类方式去获取单例对象

示例:

恶汉式:方式一

enum Singleton{   INSTANCE;//单例 }

恶汉式:方式二

class Singleton{   public static final Singleton INSTANCE = new Singleton();//单例   private Singleton(){} }

恶汉式:方式三

class Singleton{   private static final Singleton INSTANCE = new Singleton();//单例   private Singleton(){}   public static Singleton getInstance(){     return INSTANCE;   } }

懒汉式:方式一

class Singleton{   private static Singleton instance;   private Singleton(){ }   public static Singleton getInstance(){     //存在线程安全问题(多线程的时候,不一定是单例)      /*if(null == instance){       instance = new Singleton();     }     return instance;*/     if(null == instance){ //提升代码效率,避免每一次都去走同步代码块       synchronized(Singleton.class){         if(null == instance){           instance = new Singleton(); }         return instance;          }   }       return instance;     } } }

懒汉式:方式二

class Singleton{   private Singleton(){}   private static class Inner{     public static final Singleton INSTANCE = new Singleton();   }   public static Singleton getInstance(){     return Inner.INSTANCE;   } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

如何通过Java代码解析实现单例设计模式的方法?

本文共计565个文字,预计阅读时间需要3分钟。

如何通过Java代码解析实现单例设计模式的方法?

单例模式的几种实现方式:

1.饥汉式单例

方式一:枚举法获得单例对象 方式二:静态属性获得单例对象 方式三:静态方法获得单例对象

2.懒汉式单例

方式一:静态方法获得单例对象

单例模式的几种实现方式:

一:饿汉式单例

方式一:枚举方式获得单例对象

方式二:静态属性获得单例对象

方式三:静态方法获得单例对象

二:懒汉式单例

方式一:静态方法获得单例对象(线程安全)

方式二:内部类方式去获取单例对象

示例:

恶汉式:方式一

enum Singleton{   INSTANCE;//单例 }

恶汉式:方式二

class Singleton{   public static final Singleton INSTANCE = new Singleton();//单例   private Singleton(){} }

恶汉式:方式三

class Singleton{   private static final Singleton INSTANCE = new Singleton();//单例   private Singleton(){}   public static Singleton getInstance(){     return INSTANCE;   } }

懒汉式:方式一

class Singleton{   private static Singleton instance;   private Singleton(){ }   public static Singleton getInstance(){     //存在线程安全问题(多线程的时候,不一定是单例)      /*if(null == instance){       instance = new Singleton();     }     return instance;*/     if(null == instance){ //提升代码效率,避免每一次都去走同步代码块       synchronized(Singleton.class){         if(null == instance){           instance = new Singleton(); }         return instance;          }   }       return instance;     } } }

懒汉式:方式二

class Singleton{   private Singleton(){}   private static class Inner{     public static final Singleton INSTANCE = new Singleton();   }   public static Singleton getInstance(){     return Inner.INSTANCE;   } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

如何通过Java代码解析实现单例设计模式的方法?