Java mode single-instance mode:
The singleton mode ensures that a class has only one instance, provides this instance on its own and provides this instance to the system as a whole.
Characteristics:
1, a class can have only one instance
2. Create this instance yourself
3, this example is used throughout the system
singleton mode is to ensure that only one instance of a class is present in a Java application. Such a single-threaded operation is required in many operations, such as establishing a directory database connection. Some resource managers are often designed as singleton patterns.
External resources: for example, each computer can have several printers, but only one printer Spooler to prevent both print jobs from being output to the printer at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to avoid a communication port being called simultaneously by two requests. Internal resources, for example, most of the software has one (or more) attribute files to store the system configuration. Such a system should be managed by an object to manage these property files.
One example: Windows Recycle Bin.
in the entire Windows system, there can only be one instance of the Recycle Bin, the entire system uses this unique instance, and the Recycle Bin provides its own instance itself. Therefore, the Recycle Bin is an application of the singleton mode.
Two kinds of forms:
1, a Hungry man type single case
public class Singleton { private Singleton(){} //在自己内部定义自己一个实例,是不是很奇怪?//注意这是private 只供内部调用 private static Singleton instance = new Singleton(); //这里提供了一个供外部访问本class的静态方法,可以直接访问public static Singleton getInstance() {return instance;}} |
2, lazy one-case class
public
class
Singleton {
private
static
Singleton instance = null;
public
static
synchronized Singleton getInstance() {
//这个方法比上面有所改进,不用每次都进行生成对象,只是第一次
//使用时生成实例,提高了效率!
if
(instance==null)
instance=
new
Singleton();
return
instance; }
}
The second form is the lazy initialization, that is, the first call when the initial singleton, and then no longer generated.
Generally the first is more secure
My own more common way:
public
class
Singleton {
private
volatile
static
Singleton singleton;
private
Singleton(){}
public
static
Singleton getInstance(){
if
(singleton==null){
synchronized(Singleton.
class
){
if
(singleton==null){
singleton=
new
Singleton();
}
}
}
return
singleton;
}
}