java设计模式之单列模式(Singleton)

简介

本篇只是简单介绍单列模式,主要是让初学者理解单列模式,各种加锁、多实现、业务场景待以后补充。

具体实现

关键字: 只产生一个实例,构造器私有化。
构造器私有化(private),是为了禁止Singleton类外部调用构造函数。如果从Singleton类以外的代码中调用构造函数
(new Singleton),就会出现编译错误。Singleton模式在于确保任何情况下都只生成一个实例。
1.1.饿汉模式:不管你需不需要我都实例化。

public class Singleton {
    private static Singleton singleton = new Singleton();
    private Singleton() {
    	 System.out.println("生成了一个实例");
   }
    public static Singleton getInstance() {
   	 return singleton;
   }
}

测试类:

public class SingletonMain {
	public static void main(String[] args) {
		//会编译出错,构造函数Singleton()不可见(私有)
		//Singleton singleton = new Singleton();
		Singleton s1 = Singleton.getInstance();
		Singleton s2 = Singleton.getInstance();
		if(s1 == s2) {
			System.out.println("s1和s2是相同的实例");
		}else {
			System.out.println("s1和s2是不同的实例");
		}
		
	}

1.2.懒汉模式:只有你需要的时候我才给

public class SingletonLazy {
	private static SingletonLazy singletonLazy = null;
	private SingletonLazy() {
		System.out.println("生成了一个实例");
		slowdown();
	}
	//线程不安全
//	public static SingletonLazy getInstance() {
//		if(singletonLazy == null) {
//			singletonLazy = new SingletonLazy();
//		}
//		return singletonLazy;
//	}
	//线程安全,但锁的是方法,粗粒度锁
	public static synchronized SingletonLazy getInstance() {
		if(singletonLazy == null) {
			singletonLazy = new SingletonLazy();
		}
		return singletonLazy;
	}
	//先调用的停止一秒,多线程测试
	private void slowdown() {
		try {
			//sleep使当前线程让出cpu,但如果在锁内,它并不会让出锁。
			Thread.sleep(1000);
		}catch (InterruptedException e) {
			
		}
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值