Design Mode-singleton mode (02) and design mode example mode 02

Source: Internet
Author: User

Design Mode-singleton mode (02) and design mode example mode 02
Definition

Singleton Pattern is the simplest design Pattern.
Ensure a class has only one instance, and provide a global point of access to it.
Make sure that a class has only one instance and the instance is automatically instantiated and provided to the entire system.

The Singleton mode is used to ensure that only one instance exists in a class. The Singleton mode can be used to create directories, database connections, and other scenarios that require single-threaded operations to control system resources.

Category

Java features that enable the singleton mode in Java in two forms:

Hungry Chinese Singleton class: objects are instantiated when classes are loaded.
Lazy Singleton class: objects are instantiated only when a class is referenced for the first time.

Hungry Chinese Singleton type

The code for the hungry Chinese style is as follows:

Public class Singleton {private static Singleton m_instance = new Singleton (); // The constructor method is private and cannot be directly instantiated by the outside world () {}// obtain the Instance Object public static Singleton getInstance () {return m_instance ;}} through this method ;}}

In the above Code, when the class is loaded, the static variable m_instance will be initialized, the private constructor of the class will be called, and the unique instance of the singleton class will be created. The most important feature of a singleton class is that the class constructor is private, so that you do not need to use the constructor to directly create any expected instance. In addition, constructors are private, so the class cannot be inherited.

Lazy Singleton type

The lazy Singleton class is the same as the hungry Singleton class, and the class constructor is private. The difference is that the lazy Singleton class does not instantiate itself during loading, instead, it instantiates itself when it is called for the first time.

The lazy code is as follows:

 

Public class Singleton {private static Singleton _ instance = null; // The constructor is private and cannot be directly instantiated. private Singleton () {}// synchronous synchronized public static Singleton getInstance () {if (_ instance = null) {_ instance = new Singleton () ;}return _ instance ;}}

In the above Code, the static method getInstance () is synchronized in the lazy Singleton class to ensure that only one instance is created in the multi-threaded environment. For example, if the getInstance () method is not synchronized and both thread A and thread B call this method, the if (_ instance = null) statement is true, thread A and thread B will create an object respectively, and two objects will appear in the memory, which violates the singleton mode. After synchronizing with the synchronized keyword, this will not happen.

TheDifferences:

1. The Lazy Singleton class is instantiated when it is loaded, while the lazy Singleton class is instantiated when it is referenced for the first time.
2. from the perspective of resource utilization, the comparison between the ELE. Me Singleton type and the lazy Singleton type is worse (because at the beginning, an object will be instantiated to occupy system resources ), however, from the perspective of speed and response time, the hungry Chinese Singleton is better than the lazy Chinese Singleton.

3. The hungry Chinese Singleton class can be implemented in Java, but it is not easy to implement in C ++. The concept of the single-profit mode proposed by GoF is that the examples are lazy, and their books have a great impact, so that the examples of Single-case classes in Java are mostly lazy. In fact, the hungry Chinese Singleton class is more in line with the characteristics of the Java language.

Advantages of a singleton object

1. because the singleton mode only has one instance in the memory, the memory cost is reduced, especially when an object needs to be frequently created, destroyed, and the performance of creation or destruction cannot be optimized, the advantages of Singleton mode are obvious.
2. because the single-instance mode Value generates an instance, the system performance overhead is reduced. When an object requires more resources, such as reading the configuration file and generating other dependent objects, you can directly generate a singleton object at startup, and then permanently resident in the memory.
3. The Singleton mode can avoid multiple resource occupation. For example, because only one instance exists in the memory for a single file write operation, it avoids simultaneous write operations on the same resource file.
4. In Singleton mode, you can set global access points in the system to optimize and share resource access.

Disadvantages of Singleton Mode

1. The Singleton mode cannot create child classes, and it is difficult to expand. To scale out, there is basically no second way to implement it except to modify the code.
2. The Singleton mode is not good for testing. In a parallel development environment, if the class in the single-sample mode is not completed, the program cannot be tested. classes in the single-sample mode usually do not implement interfaces, this also prevents the use of mock to virtualize an object.
3. The Singleton mode conflicts with the single responsibility principle. A class should only implement one logic, regardless of whether it is a singleton or not. Whether the singleton mode is used depends on the environment and Singleton mode.

Use Cases of Singleton Mode

In a system, if a class is required to have only one instance, multiple instances may cause adverse reactions. In this case, the single-instance mode can be used. Typical scenarios are as follows:

1. environment where a unique serial number is required.
2. an access point or shared data is required for the entire project. (For example, counters on Web pages)
3. Creating an object consumes too many resources, such as accessing IO and databases.
4. You can use the singleton mode to define a large number of static constants and static methods (such as tool classes.

This is a misleading thread example. After modification, it becomes very simple.

Public class CounterSingleton {
// Load the private static CounterSingleton singleton = new CounterSingleton () in a lazy manner; // private structure to prevent generating the private CounterSingleton () {}// obtain the public static CounterSingleton getInstance () Class () {return singleton ;}
// The private variable of the object public int count = 0; // The method of the lazy object public synchronized void inc () {// Add access count ++; // System. out. println (count );}

Public int getCount (){
Return count;
}

} Public class Counter {public static void main (String [] args) {long time_s = System. currentTimeMillis (); // start 1000 threads at the same time and perform I ++ calculations to see the actual result for (int I = 0; I <1000; I ++) {new Thread (new Runnable () {@ Override public void run () {CounterSingleton. getInstance (). inc ();}}). start ();} // The value of each running operation may be different, and the result may not be 1000 (if the inc method does not have sychonized, the count is actually not 1000) System. out. println ("running result: CounterSingleton. count = "+ CounterSingleton. getInstance (). getCount (); System. out. println ("Time consumed:" + (System. currentTimeMillis ()-time_s ));}}

Source code

Related Article

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.