Java单例模式的实现

所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例。

饿汉式:
class Bank{
	
	//1.私化类的构造器
	private Bank(){
		
	}
	
	//2.内部创建类的对象
	//4.要求此对象也必须声明为静态的
	private static Bank instance = new Bank();
	
	//3.提供公共的静态的方法,返回类的对象
	public static Bank getInstance(){
		return instance;
	}
}





//使用同步机制将单例模式中的懒汉式改写为线程安全的
public class SafeOfThread {
    //    私有化构造器
    private SafeOfThread() {
    }

    //    定义同步监视器
    static Object object = new Object();

    //    定义单例对象并赋值为null
    private static SafeOfThread instance = null;

    //    定义方法给单例对象初始化,并返回单例对象----同步代码块
    public static SafeOfThread getInstance() {
        synchronized (object) {
            if (instance == null) {
                instance = new SafeOfThread();
            }
            return instance;
        }
    }

//    优化效率
//    public static SafeOfThread getInstance() {
//        if (instance == null){
//            synchronized (object) {
//                if (instance == null) {
//                    instance = new SafeOfThread();
//                }
//            }
//        }
//        return instance;
//    }

//    使用同步方法保证线程安全
//    public static synchronized SafeOfThread getInstance() {
//            if (instance == null) {
//                instance = new SafeOfThread();
//            }
//            return instance;
//    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值