Design Pattern: Singleton Mode

Source: Internet
Author: User

Http://www.35java.com/zhibo/forum.php? MoD = viewthread & tid = 267 & extra = Page % 3d2

Singleton is a standalone language, that is, only one person, which is applied to the object-oriented language. It is usually translated as a singleton instance ).

Most of the time, you need Singleton mode, such as printer management. You want only one printspooler in the program to prevent two printing operations from being input to the printer at the same time. For example, database management, the connection object consumes resources. You want only one connection object in the program. All other programs connect to the database through this object, to avoid resource consumption caused by repeated opening of connected objects. For example, if the system program reads attribute files, you can use a single object to read attribute content, other parts of the program require attribute data to this object, rather than reading the attribute data by themselves.

taking the printer design as an example, some designers use global variables to create instances and randomly use them in the program. Although JAVA does not support global variables, however, by packing objects in a category, some people may adopt the following method:
public class printspooler {
Public printspooler () {
//....
}

Public connection getspooler () {
....
}
}

public class globalobject {
private printspooler;
Public globalobject () {
printspooler = new printspooler ();
...
}

Public void getprintspooler (){
Return printspooler;
}
}

No matter whether the global variables or the above examples are used, it cannot be guaranteed that only one instance is generated. You may be careful not to make this error, however, partners working with you may use Construction Methods intuitively to generate a printspooler instance.

Singleton mode ensures that there is only one instance in a category and provides a method to access this instance.

A singleton implementation is Java in Java. lang. runtime class. Each Java program has a unique runtime object during execution. You can obtain this object through the static getruntime () method provided by it. For example:
Runtime runtime = runtime. getruntime ();

After obtaining the runtime object, you can execute some external commands, perform garbage processing, and other commands through it. You can enable the runtime. Java class. The first lines are written as follows:
Public class runtime {
Private Static runtime currentruntime = new Runtime ();

Public static runtime getruntime (){
Return currentruntime;
}

/** Don't let anyone else instantiate this class */
Private Runtime (){}

// Below
}

The above structure is designed in singleton mode, and its structure is described in UML as follows:

As shown above, Java usesStatic FactoryTo get the runtime object. The constructor of Runtime is declared as private, which can prevent others from using the constructor to create an instance. A more general UML structure is used to represent a single instance, as shown in:

There are several methods to implement the above structure. You can create an object when you need the instance for the first time, that is, use the so-called lazy initialization:
Public class Singleton {
Private Static Singleton instance = NULL;

Private Singleton (){
//....
}

Public static Singleton getinstance (){
If (instance = NULL ){
Instance = new Singleton ();
}

Return instance;
}

//. Other implementations
}

The above implementation is applicable to single-thread programs. In multi-thread programs, the following statements are written under competing resources of multiple execution threads, two or more instances may still be generated, for example:
Thread1: If (instance = NULL) // true
Thread2: If (instance = NULL) // true

Thread1: instance = new Singleton (); // generate an instance
Thread2: instance = new Singleton (); // generates another instance.

Thread1: Return instance; // return an instance
Thread2: Return instance; // return another instance

In a multi-thread environment, to avoid simultaneous resource competition, multiple instances are generated as shown above, and the synchronization mechanism is added:
Public class Singleton {
Private Static Singleton instance = NULL;
Private Singleton (){}
Synchronized static public Singleton getinstance (){
If (instance = NULL ){
Instance = new Singleton ();
}
Return instance;
}
}

However, this simple writing method is not suitable for services such as servers that run a lot of threads, and the synchronization mechanism will cause considerable low efficiency. In order to take into account Singleton, lazy initialization and performance problems, therefore, the double-check locking mode is available:
Public class Singleton {
Private Static Singleton instance = NULL;
Private Singleton (){}
Public static Singleton getinstance (){
If (instance = NULL ){
Synchronized (singleton. Class ){
If (instance = NULL ){
Instance = new Singleton ();
}
}
}
Return instance;
}
}

The runtime class in Java is much simpler. It discards lazy initialization. If your instance is not initialized for a long time, you can use this method:
Public class Singleton {
Private Static Singleton instance = new Singleton ();

Private Singleton (){
//....
}

Public static Singleton getinstance (){
Return instance;
}

// Other implementations
}

Singleton has a simple concept but is widely used. Therefore, you must consider and adjust the actual environment. We recommend that you take a look at Singleton's article discussion .

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.