好好学习单例设计模式

作用

保证则程序执行过程中,一个类仅有一个实例对象,并且提供一个访问这个类的全局访问点。这样有效避免了一个全局被使用的类,频繁的被创建和销毁。

好处

  • 提升运行效率;
  • 实现数据共享;
  • 节省系统资源;

缺点

  • 没有接口,不能继承,与单一职责原则冲突(一个类,只有一个引起它变化的原因)。

设计思想

判断系统是否已经存在这个类的实例,如果存在,则直接返回;若不存在,则创建后返回。

关键代码

将无参构造函数私有化。

写法

懒汉式(线程安全)
  • 对象只有被调用时才去创建;
public class Singleton{
	//由于对象需要被静态方法调用,把对象设置为static
	//由于对象是static,会被(类名.对象名)直接访问到,所以必须设置其访问权限为private
	private volatile static  Singleton singleton;
	
	//构造方法私有化,其他类不能实例化这个类
	private  Singleton();
	
	//对外提供访问入口
	public static  Singleton  getInstance(){
		//添加逻辑:如果实例化过,直接返回
		if(singleton==null){
			//防止多线程if同时成立,加锁
			Synchronized(Singleton.class){
				if(singleton==null){
					singleton=new Singleton();
				}
			}
		}
		return singleton;
	}
}
Singleton singleton = Singleton.getInstance();

由于添加了锁,所以效率低

懒汉式(非线程安全)
public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  

    public static Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}

饿汉式
  • 在类加载时就对类进行实例化;
  • 解决了懒汉式中多线程访问可能出现同一个对象和效率低访;
public class Singleton{
	//类加载时进行实例化
	private  static  Singleton singleton = new Singleton();
	
	private  Singleton();
	
	//对外提供访问入口
	public static  Singleton  getInstance(){
			return singleton;
	}
}

创建线程安全的单例

懒汉
public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
    public static synchronized Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}
静态内部类
public class Singleton {  
    private static class SingletonHolder {  
    	private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    
    public static final Singleton getInstance() {  
    	return SingletonHolder.INSTANCE;  
    }  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值