Singleton

本文介绍了单例模式的概念及其在不同场景中的应用,包括资源管理和数据共享等。通过两个示例展示了如何实现线程安全的单例模式,并解释了其重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Singleton pattern
This code demonstrates how the Singleton pattern can be used to create a counter to
provide unique sequential numbers, such as might be required for use as primary keys in a database:
// Sequence.java
public class Sequence {
	private static Sequence instance;
	private static int counter;

	private Sequence() {
		counter = 0; // May be necessary to obtain
		// starting value elsewhere...
	}

	public static synchronized Sequence getInstance() {
		if (instance == null) // Lazy instantiation
		{
			instance = new Sequence();
		}
		return instance;
	}

	public static synchronized int getNext() {
		return ++counter;
	}
}
Some things to note about this implementation:
* Synchronized methods are used to ensure that the class is thread-safe.
* This class cannot be subclassed because the constructor is private. This may or may
not be a good thing depending on the resource being protected. To allow subclassing,
the visibility of the constructor should be changed to protected.

以上源自《Design Patterns》,主要是介绍设计模式中单态设计,单态设计主要是限制一个类只能允许有一个实例化对象,这个有时候非常有必要的,比如,操作系统的文件管理中,如果我要删除一个文件,那么对于一些多进程多线程系统来说,就不可避免的会产生多个线程或者进程同时对文件进行操作,这样就会产生混乱,但是如果我们采用单态设计,那么所有的文件操作都必须通过唯一的实例进行,这样就会避免上面的混乱发生。

单态设计一般在一下几种情况中将被用到:

1,控制实例产生的数量,以节省资源。

2,控制多线程对资源的并发访问。

3,通过一个实例实现数据共享。

一个简单示例:

class Student {
	private String name;

	private Student() {
	}

	/*
	 * 方式一: 这种形式是线程安全的,但是在程序已启动的时候就会初始化。 
	 * private static Student stu = new Student();
	 * public static Student getInstance() { return stu; }
	 */

	/*
	 * 方式二: 这种方式由于是在同步块中进行实例化,所以是线程安全的 
	 * private static Student stu;
	 * public static synchronized Student getInstance() { if (stu == null) { stu
	 * = new Student(); } return stu; }
	 */

	/*
	 * 方式三: 这种形式不必运用同步块,一样能达到线程安全的效果
	 */
	private static class SingletonHold {
		static Student stu = new Student();
	}

	public static Student getInstance() {
		return SingletonHold.stu;
	}//~

	public void setName(String n) {
		SingletonHold.stu.name = n;
	}

	public String getName() {
		return SingletonHold.stu.name;
	}

}

public class Singleton {
	public static void main(String[] args) {
		Student stu = Student.getInstance();
		System.out.println(stu.getName());
		stu.setName("sugite");
		System.out.println(stu.getName());
		Student newStu = Student.getInstance();
		System.out.println(newStu.getName());
	}
}

输出结果:

null
temple
temple

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值