java单例设计模式 Java实现单例设计模式方法解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java单例设计模式 Java实现单例设计模式方法解析

dirsoen   2021-04-21 我要评论

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

一:饿汉式单例

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

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

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

二:懒汉式单例

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

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

示例:

恶汉式:方式一

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;
  }
}

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们