Design mode-Singleton mode (Singleton pattern)

Source: Internet
Author: User

This article by @ To stay for the original, reproduced please indicate the source.

A brief introduction to the singleton model

The singleton mode guarantees that there is only one instance of our class, and we can get this instance at any time, which guarantees that our class has and only one instance is quite important at some point, such as we only need a thread pool instead of two and so on, but we should also note that The singleton pattern is less suitable than we thought, so please do not misuse this pattern.

Some characteristics of a singleton pattern

1, the singleton mode ensures that there is only one instance in our program.

2, we can get this example at any time.

3, the Singleton mode construction method is private, so the Singleton class cannot exist as a parent without destroying the private condition.

The definition and basic structure of singleton pattern

There is only one class in a singleton pattern, so there is actually no structure that says = =, but we can still look at its definition.

definition: Make sure that the class has and has only one instance, and that it is guaranteed access to the instance at all times. (This sentence seems to have appeared a good time =)

The definition and structure of the singleton pattern are very simple, and we don't even need to take extra examples to understand them, but we still have a lot of details to pay attention to when we are actually implementing the singleton , so let's go on to the actual code.

Code implementation for singleton Mode (Java edition)

Code implementation

1  Public classMysingleten {2     public Static Mysingleten Instance=null; // variables pointing to instances  3     PrivateMysingleten () {}// privatization constructor, but other code cannot create an instance of this class  4     public Static Mysingleten getinstance () {// We have obtained this single-case method. 5         if(NULL==instance) {6Instance=NewMysingleten ();7         }8         returninstance;9     }Ten      Public voidMyFunction () {// representative of general method   OneSystem.out.println ("I am a singleton, this is my method"); A     } -}

This is the way we usually call it: lazy-type

Why is it? Because it does not generate its own instance until it is first called (as if we were going to write our homework every time we had to hand in our homework, it was lazy = ̄ω ̄=)

Note: lazy is not thread-safe

For example: Imagine a situation where thread a executes to line 5th of the code, determines success, the CPU switches when it is ready to enter line 6th, and thread B happens to execute this code, then it is clear that instance or ==null's bathroom thread B successfully created a instance instance, the result, When the CPU is cut back to thread A, the trouble is that thread a continues to execute line 6th and creates an instance of instance, overwriting the original, which is likely to lead to unexpected problems.

Therefore, we must find a way to solve this problem, here we provide the following several ideas.

a hungry man type: It is not created until it is used, but it is created at the beginning of the program (hungry for this instance, so it is called Hunger (Chi) Han style)

1  Public classMysingleten {2      Public StaticMysingleten instance=NewMysingleten (); // generate this variable from the beginning there is no threading problem.  3     PrivateMysingleten () {}4     public Static Mysingleten getinstance () {5         returninstance;6     }7      Public voidMyFunction () {8System.out.println ("I am a singleton, this is my method");9     }Ten}

Synchronized method: directly before the lazy getinstance method with synchronized modifier, so that can solve the thread safety problem, this solution is the simplest, But the efficiency is very low, because only the first time to create an instance of this synchronized is necessary, when the instance is created, this synchronized only the slow speed of the action.

1  Public classMysingleten {2      Public StaticMysingleten instance=null;3     PrivateMysingleten () {}4     public Static  synchronizedMysingleten getinstance () {5         if(NULL==instance) {6Instance=NewMysingleten ();7         }8         returninstance;9     }Ten      Public voidMyFunction () { OneSystem.out.println ("I am a singleton, this is my method"); A     } -}

Double Locking method: on the basis of lazy , we can use two locks to control the acquisition and creation of the single case, because only need to pay attention to thread safety in the first creation of a single case, then, we lock in the inner layer with synchronized to control, In the outer lock use if(null==instance) to determine if this instance exists, thus eliminating the synchronized in later wasted synchronization time

1  Public classMysingleten {2      Public volatile StaticMysingleten Instance=null; // Note This adds the volatile keyword  3     PrivateMysingleten () {}4     public Static Mysingleten getinstance () {5         if(NULL= = Instance) {//outer Lock to determine if an instance has been created6             synchronized(Mysingleten.class) {//The inner lock controls the synchronization between threads, and the instance is created without the opportunity to run, eliminating the redundant cost of inter-thread synchronization7                 if(NULL==instance)//it needs to be checked again because it is very likely that thread A is here when thread B has passed the outer if. 8Instance =NewMysingleten ();9             }Ten         } One         returninstance; A     } -      Public voidMyFunction () { -System.out.println ("I am a singleton, this is my method"); the     } -}

Comparison of static global variables and singleton patterns

1, a static global variable does not guarantee that the object is unique (since you can create this static global variable, it means that the constructor of the class is not private).

2, redundant global variables can cause namespace pollution.

3, the global variable is always present and will occupy memory all the time, while the singleton mode can be used to create an instance of the singleton when the access is achieved.

4, the object generated by the singleton pattern is saved in the heap, but the static global variables are stored in the stack.

Comparison of static members and singleton patterns

1, using a class of static members to simulate a singleton, it is not possible to implement other interfaces, this usage is divorced from the object-oriented thinking (unless the application and implementation of this class does not require object-oriented thinking then you can do so).

2, static members can selectively divide the contents of the class into the need to ensure uniqueness and do not need to ensure uniqueness, and sometimes more flexible.

Java version compatibility reminders

The garbage collection mechanism before 1,java1.2 is bug-free, causing the singleton instance to be purged without a global reference.

Many JVM implementations of volatile before 2,java1.4 cause the double lock method to fail

Some controversies about the singleton mode

If you've just finished reading my blog post and feel happy to have a little bit of a harvest (if that's true, I'd be happy too?) (^∇^*)), I think you can calm down first (fog = =), single-case design mode in the network is a very controversial mode, some people think that this mode violates too many design principles, some people feel that he increased the coupling of the code and so on, but sometimes we do need a single example to give us some features, Originally Bo Master want to read some other people's article to help you summarize the discussion on the network, the results Bo Master found these discussions are too many, and more miscellaneous, all kinds of sound, stackoverflow on a similar problem with "the answer to this question is based on personal choice rather than experience-based ... "and was closed, so bloggers think or choose some bloggers feel better than the connection to everyone, let you think better. (The relevant discussion of the connection is placed in the resources, if it is not enough, you can directly Google "singleton why Bad")

Resources:

1, "Head First design mode"

2,https://agiletribe.wordpress.com/2013/10/08/dont-abuse-singleton-pattern/about when to use singleton mode

3,https://www.cnblogs.com/seesea125/archive/2012/04/05/2433463.html about why using a singleton mode without static methods

4,https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons discussion on the dispute of single case model

5,https://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern discussion of Singleton and static classes

Design mode-Singleton mode (Singleton pattern)

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.