分享

java几种方式实现单例设计模式

 Coder编程 2020-06-09

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

一:饿汉式单例

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

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

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

二:懒汉式单例

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

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

 

示例:

恶汉式:方式一

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;

  }

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多