Singleton mode in Design Mode

Source: Internet
Author: User

Singleton mode in Design Mode

Tom spent his time on the company's tasks over the past few days, so he did not write any articles about the design model. Now he is familiar with the system process, you don't need to spend most of your time on the task, but you also have some time to learn the design model. Today, we will add the previous Singleton model!

He liked to use Baidu encyclopedia to read the meaning of the term. If he couldn't understand it, he would try to find another blog. This is no exception, open the singleton mode in Baidu encyclopedia and search! The page immediately pops up!

Definition:

This mode aims to make an object of A Class A unique instance in the system. To achieve this, you can start by instantiating the client. Therefore, we need to use a mechanism that only allows the generation of unique instances of the object class to "Block" access to all objects to be generated. Use the factory method to restrict the instantiation process. This method should be a static method (class method), because it is meaningless to let the class instance generate another unique instance. Key words --- "unique", "static", and "Factory"

"It seems that every design pattern has such a relationship !", Chubby said to himself, watching and singing "you and him are still disconnected ...",For some classes in the system, it is very important to have only one instance. For example, a system may have multiple print tasks, but only one job is in progress; A system can have only one window manager or file system. A system can have only one timing tool or ID (serial number) generator. For example, only one task manager can be opened in Windows. If you do not use the window object uniqueness mechanism, multiple windows will pop up. If the content displayed in these windows is completely consistent, it is a duplicate object, wasting memory resources; if the content displayed in these windows is inconsistent, it means that the system has multiple States at a certain moment, which is inconsistent with the actual status. It may also cause misunderstandings to the user, and the user does not know which one is the real status. Therefore, it is important to ensure the uniqueness of an object in the system.

He was not satisfied with seeing this fat guy, because he remembered that when he was a freshman and his roommate playing CF, he sometimes cut out the game and press "ctrl + alt + delete" and then "summon out" the task manager, at that time, there was more than one window, and more than a dozen windows came out! He quickly tested it in his new notebook. Hey, this time, only one window is displayed. It's strange that he has Baidu and probably understood the cause of this problem, because the computers used in the freshman year are a little old, it is a little hard to run a game, and then you have to summon the task manager, the computer is too much to eat, so you press a few times, how many windows are displayed! To put it bluntly, it is because the computer is always on the verge of a crash that some abnormalities may occur!

"It turned out to be like this ."

The Singleton mode has three key points:

A class can only have one instance. It must create this instance by itself. It must provide this instance to the entire system.

From the specific implementation perspective:

Only a private constructor class definition contains a static private object of this class. This class provides a static common function for creating or obtaining its own static private object.

Xiaopang looked at some opinions on the singleton mode written by bloggers and summed up some

The Singleton mode is divided into the most common three types: the hunger mode, the lazy mode, and the dual lock mode. Chubby is more interested in the hunger mode and the lazy mode. He hurriedly implemented these two codes. The Code is as follows:

Hunger Mode

/*** Hunger @ author Administrator **/public class Singleton {String str = null; private static Singleton instance = new Singleton (); private Singleton () {} public static Singleton getInstance () {return instance;} public void print () {System. out. println (str);} public String getStr () {return str;} public void setStr (String str) {this. str = str ;}}
Lazy mode:

/*** LazySingleton mode * @ author Administrator */public class LazySingleton {String str = null; private static LazySingleton instance = null; public static LazySingleton getInstnce () {if (instance = null) {instance = new LazySingleton ();} return instance;} public void print () {System. out. println (str);} public String getStr () {return str;} public void setStr (String str) {this. str = str;} private LazySingleton (){}}
Tom carefully analyzed the two codes,
When the test code has not called this class in the hunger mode, the new instance has been released! "

Lazy mode does not have a new instance, but when the test code calls this class, it first makes a judgment on the instance. If there is a direct return, if there is no, then a new instance is returned, "Oh, it's also lazy, but it's better than ELE. Me."

Ele. Me and lazy understand what is the dual lock?

The thread problem is introduced here. There is no error in the preceding single thread. What if multiple threads use the single example in the lazy mode at the same time? The existing threads A and B call this Singleton class at the same time, and judge the instance at the same time. Of course, it is null, so A and B get the instance at the same time. To solve this problem, the double lock occurs, that is, the instance is judged twice. The Code is as follows:

/*** Double lock mode ** @ author Administrator **/public class SingletonObject {private static SingletonObject obj; private static Object lock = new Object (); private SingletonObject () {} public static SingletonObject getInstance () {if (obj = null) {synchronized (lock) {if (obj = null) {obj = new SingletonObject ();}}} return obj ;}
This time I made two judgments on the instance, and I am not afraid of many processes!
The class diagram of the singleton mode is as follows:




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.