java 单例模式

单例模式

只允许创建一个该类的对象

  • 饿汉式
public class Singleton {
    //声明该类的唯一实例
    private static Singleton instance  = new Singleton();
    private Singleton(){

    }
   
   // 对外提供访问方法
    public static Singleton getInstance(){
        return instance;
    }
}
class Test{
    public static void main(String[] args) {
        Singleton cc1 = Singleton.getInstance();
        Singleton cc2 = Singleton.getInstance();
        System.out.println(cc1 == cc2);  //true
    }
}
  • 懒汉式
//懒汉(通过synchronized 实现线程安全)
class Singleton2 {
	//声明一个该类的唯一的实例
	private static Singleton2 instance = null;
	//私有化构造器
	private Singleton2() {
	}
	//对外提供一个访问方法
	public  static synchronized Singleton2 getInstance() {
		if(instance==null) {
			instance = new Singleton2();
		}
		return instance;
	} 
}

//懒汉模式(通过静态内部类实现线程 安全)
class Singleton3{

	public Singleton3() {
		System.out.println("执行.....");
	}

	private static class Holder{
		static  Singleton3 s = new Singleton3();
	}

	public static Singleton3 getInstance() {
		return Holder.s;
	}

} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值