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:
* 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.
输出结果:
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