A singleton pattern in Java design mode

Source: Internet
Author: User

Single-Case mode

Singleton mode (Singleton pattern) is one of the simplest design patterns in Java. This type of design pattern belongs to the Create pattern, which provides an optimal way to create an object.
This pattern involves a single class that is responsible for creating its own objects, while ensuring that only a single object is created. This class provides a way to access its only object, which can be accessed directly without instantiating an object of that class.
Attention:
1, the Singleton class can have only one instance.
2, the Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to all other objects.

Introduced

Intent: Ensure that a class has only one instance and provides a global access point to access it.
Primary solution: A globally used class is frequently created and destroyed.
When to use: when you want to control the number of instances, save system resources.
How to solve: determine if the system already has this singleton, if there is a return, if not created.
Key code: The constructor is private.

Application Examples:

1, a party can only have one chairman.

2, Windows is multi-process multithreading, in the operation of a file, it is inevitable that multiple processes or threads simultaneously manipulate a file, so all files must be processed through a unique instance.

3, some Device Manager is often designed as a single-case mode, such as a computer has two printers, in the output will be processed can not be two printers to print the same file.

Advantages: 1, there is only one instance in memory, reduce the memory overhead, especially the frequent creation and destruction of instances (such as the management of the school home page cache). 2, avoid the multiple occupation of resources (such as write file operations).

Cons: No interface, no inheritance, conflict with a single responsibility principle, a class should only care about internal logic, not how to instantiate outside.
Usage Scenario: 1, requires the production of a unique serial number. 2, the counter in the WEB, do not have each refresh in the database Riga once, with a single case first cache up. 3, the creation of an object needs to consume too much resources, such as I/O and database connection.

Note: the getinstance () method requires the use of synchronous lock synchronized (Singleton.class) to prevent multi-threaded simultaneous entry resulting in instance being instantiated multiple times.

One, lazy type single case

1      Public classSingleton {2         PrivateSingleton () {}3         Private StaticSingleton single=NULL; 4        5          Public StaticSingleton getinstance () {6              if(single =NULL) {    7Single =NewSingleton (); 8              }9 Ten             returnSingle ;  One         }   A}
View Code

Singleton by restricting the construction method to private to prevent the class from being instantiated externally, the unique instance of Singleton can only be accessed through the getinstance () method within the same virtual machine scope.
(In fact, the Java reflection mechanism is the ability to instantiate a class constructed as private, which basically invalidates all Java Singleton implementations.) This issue is not discussed here, and it is deceiving to assume that the reflection mechanism does not exist. )

However, the above-mentioned lazy singleton implementation does not take into account the thread safety problem, it is thread insecure, the concurrency environment is likely to have multiple singleton instances, to achieve thread safety, there are the following three ways, is to getinstance this method of transformation, to ensure that the lazy single-case thread safety, If you first contact the singleton mode, the thread safety is not very understanding, you can skip the following three strips, to see the A hungry man-type singleton, and then look back to consider the issue of thread safety:

1, on the GetInstance method plus synchronization

1      Public Static synchronized Singleton getinstance () {  2          ifnull) {    3              New  Singleton ();   4          }    5 6         return Single ;   7     }  
View Code

2. Double check Lock

1      Public StaticSingleton getinstance () {2         if(Singleton = =NULL) {    3             synchronized(Singleton.class) {    4                if(Singleton = =NULL) {    5Singleton =NewSingleton (); 6                }    7             }    8         } 9    Ten         returnSingleton;  One}
View Code

3. Static Inner class

1      Public classSingleton {2         Private Static classLazyholder {3            Private Static FinalSingleton INSTANCE =NewSingleton (); 4         }5 6         PrivateSingleton () {};7     8          Public Static FinalSingleton getinstance () {9            returnlazyholder.instance; Ten         }     One}
View Code

Two, a hungry man type single case

1      Public classSingleton1 {2         PrivateSingleton1 () {}3         Private Static FinalSingleton1 single =NewSingleton1 (); 4 5          Public StaticSingleton1 getinstance () {6             returnSingle ; 7         }  8}
View Code

A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is inherently thread-safe.

Three, a hungry man and lazy-type difference

From the name of the A hungry man and the lazy,

A hungry man is the class once loaded, the singleton initialization is completed, to ensure that the getinstance, the singleton is already exist,

And lazy idle, only when the call getinstance, only to go back to initialize the singleton.

In addition differentiates the following two ways from the following two points:


1. Thread Safety:

A hungry man is inherently thread-safe and can be used directly for multithreading without problems.

The lazy type itself is non-thread-safe, in order to achieve thread safety there are several ways to write, respectively, the above 1, 2, 3, these three implementations in the resource load and performance of some differences.

2. Resource Loading and performance:

A hungry man a static object is instantiated at the same time as the class is created, and will occupy a certain amount of memory regardless of whether the singleton will be used later, but correspondingly, the speed will be faster on the first call because its resources have been initialized,

And the lazy type as the name implies, will delay loading, in the first use of the singleton when the object will be instantiated, the first call to do the initialization, if you want to do more work, performance will be somewhat delayed, and then the same as the A Hungry man type.

There are some differences between the three implementations of 1, 2 and 3,

1th, in the method call added synchronization, although thread security, but each time to synchronize, will affect performance, after all, 99% of the case is not required to synchronize,

2nd, two null checks were made in getinstance to ensure that only the first invocation of the singleton will be synchronized, which is also thread-safe, while avoiding the performance loss of each synchronization

3rd, using the ClassLoader mechanism to ensure that there is only one thread when initializing instance, so it is thread-safe, and there is no performance loss, so I tend to use this one.

What is thread safety?

If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe.

Or, the interface provided by a class or program is atomic to the thread, or the switch between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization, which is thread-safe.

Test code:

1  Public classSingleton {2 3String name =NULL;4     5     PrivateSingleton () {};6     7     Private  StaticSingleton instance =NewSingleton ();8     9     Private StaticSingleton getinstance () {Ten         returninstance; One     } A      -      PublicString GetName () { -     returnname; the     } -  -      Public voidsetName (String name) { -      This. Name =name; +     } -      +      Public voidPrintname () { ASystem.out.println ("Name is:" +name); at     } -  -      Public Static voidMain (string[] args) { -  -Singleton S1 =singleton.getinstance (); -S1.setname ("ABCD"); inSingleton s2 =singleton.getinstance (); -S2.setname ("Efgh"); to              + s1.printname (); - s2.printname (); the              * System.out.println (S1); $ System.out.println (S2);Panax Notoginseng              -     } the  + } A     
View Code

A singleton pattern in Java design mode

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.