设计模式——单例模式

保证一个类只存在一个实例化对象,并提供一个方法来访问这个对象,实现受控访问。

懒汉模式

懒汉模式指的是在需要获取对象(调用getInstance)的时候才会创建,即延迟加载。

成员必须是static,才会具有唯一性。

构造函数是private,外部无法访问,也就无法创建实例。

getInstance必须是static,才能不通过实例来调用。

public class Singleton {
	private static Singleton instance = null;
	
	private Singleton() {
		System.out.println("create the single instance");
	}
	
	public static Singleton getInstance() {
		if (instance == null)
		{
			instance = new Singleton();
		}
		return instance;
	}
}

测试代码,判断是否是同一实例。

public class SingletonTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Singleton singleton1 = Singleton.getInstance();
		Singleton singleton2 = Singleton.getInstance();
		System.out.println(singleton1.hashCode());
		System.out.println(singleton2.hashCode());
		if (singleton1 == singleton2) {
			System.out.println("the same instance");
		}
	}
	
}

构造函数只被调用一次,hash值相同,if判断结果也是true。

create the single instance
1627800613
1627800613
the same instance

饿汉模式

饿汉模式下,static成员在类被初始化时,就会被创建,可能会造成资源浪费,但是不会在多线程环境下产生多个实例。getInstance只负责返回它的引用。

//饿汉模式 
public class Singleton {
	private static Singleton instance = new Singleton();
	
	private Singleton() {
		System.out.println("create the single instance");
	}
	
	public static Singleton getInstance() {
		return instance;
	}
}

懒汉模式-同步锁

在多线程环境下,懒汉模式无法保证线程安全,有可能创建出来多个实例,这时候就需要加上一个同步锁。

//同步锁
public class Singleton {
	private static Singleton instance = null;
	
	private Singleton() {
		System.out.println("create the single instance");
	}
	
	public synchronized static Singleton getInstance() {
		if (instance == null)
		{
			instance = new Singleton();
		}
		return instance;
	}
}

创建线程类

public class TestThread extends Thread{
	@Override
	public void run() {
		System.out.println(Singleton.getInstance().hashCode());
	}
}

测试

public class SingletonTest {

	public static void main(String[] args) {
		
		//multi thread test
		TestThread thread1 = new TestThread();
		TestThread thread2 = new TestThread();
		TestThread thread3 = new TestThread();
		thread1.start();
		thread2.start();
		thread3.start();
	}
	
}

结果

create the single instance
1064288774
1064288774
1064288774

懒汉模式-双检锁

加锁会导致每次想要得到实例时,都要试图加上一个同步锁,然而我们只是在实例可能还没有被创建的情况下,加锁来确定是否已经存在一个实例,如果实例已经存在,就没有必要进行加锁操作。根据这一思路,可以加入一层判断,并使用synchronized这个关键字锁住代码块。

有问题

双重检查锁定与延迟初始化

单例---被废弃的DCL双重检查加锁

//双检锁
public class Singleton {
	private static Singleton instance = null;
	
	private Singleton() {
		System.out.println("create the single instance");
	}
	
	public static Singleton getInstance() {
		if (instance == null) {
			synchronized (Singleton.class) {
				if (instance == null)
					instance = new Singleton();					
			}
		}
		return instance;
	}
}

静态内部类

序列化和反序列化单例模式

静态代码块

枚举方法

参考

java多线程(一)——线程安全的单例模式

JAVA_多线程_单例模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值