In-depth research on Singleton mode and in-depth research on Mode

Source: Internet
Author: User

In-depth research on Singleton mode and in-depth research on Mode

The Singleton mode is a common software design mode. Its core structure only contains a special class called Singleton class. The Singleton mode ensures that there is only one instance in a class in the system and the instance is easy to access, so as to conveniently control the number of instances and save system resources. If you want to have only one class object in the system, the singleton mode is the best solution.

 

Singleton mode is one of the simplest forms of design patterns. 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.

Static uniqueInstance is the only instance of singleton, and static sharedInstance will return it to the client. Generally, sharedInstance checks whether the uniqueInstance has been instantiated. If not, it generates an instance and returns the uniqueInstance.



 

Motivation is very important for some classes in the system. For example, a system can have multiple print tasks, but only one task is working; 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. How can we ensure that a class has only one instance and this instance is easy to access? Defining a global variable ensures that objects can be accessed at any time, but it cannot prevent us from instantiating multiple objects. A better solution is to let the class itself be responsible for saving its unique instance. This class can ensure that no other instance is created, and it can provide a method to access the instance. This is the model motivation of the singleton mode. There are three main points of Singleton mode. One is that a class can only have one instance, and the other is that it must create the instance on its own; third, it must provide the instance to the entire system. From a specific implementation perspective, there are three points: first, the class in singleton mode only provides private constructors, and second, the class definition contains a static private object of this class, third, this class provides a static common function for creating or obtaining its own static private object. Advantages and disadvantages Advantages I. instance ControlThe Singleton mode prevents other objects from instantiating copies of their own Singleton objects, so that all objects can access a unique instance. Ii. FlexibilityBecause classes control the instantiation process, classes can flexibly change the instantiation process. Disadvantages I. overheadAlthough the number is small, if you want to check whether there is a class instance for each object request reference, you still need some overhead. You can solve this problem by using static initialization. Ii. Possible development ObfuscationWhen using a singleton object (especially the objects defined in the class library), developers must remember that they cannot use NewKeyword instantiation object. Because the source code of the library may not be accessible, application developers may accidentally find that they cannot directly instantiate this class. Instance Singleton mode in JavaIn java, you can use the following method to create a class instance in singleton mode: public class MyBean {private static MyBean instance = null; private MyBean () {// do something} public static synchronized MyBean getInstance () {if (instance = null) {instance = new MyBean () ;}return instance ;}} this function is required when only one instance of a class can be used. Why do we only need one? Some people say it is to save memory, but this is only a benefit of the singleton mode. Only one instance does reduce memory usage, but I don't think this is used Singleton Mode. I think Singleton ModeWhen there are multiple instances that may cause program logic errors. For example, how can an ordered number generator be allowed to have multiple numbers in one application? The Singleton mode ensures that only one instance of a Class exists in a Java application. Generally, Singleton mode has three forms: the first one is also a common form. Public class Singleton {private static Singleton instance = null; private Singleton () {// do something} public static Singleton getInstance () {if (instance = null) {instance = new Singleton ();} return instance ;}} second form: public class Singleton {// define your own instance internally, private static Singleton instance = new Singleton (); private Singleton () {// do something} // a static method for external access to this class is provided, you can directly access public static Singleton ge TInstance () {return instance ;}} third form: double lock form. Public class Singleton {private static Singleton instance = null; private Singleton () {// do something} public static Singleton getInstance () {if (instance = null) {synchronized (Singleton. class) {if (null = instance) {instance = new Singleton () ;}} return instance ;}// In this mode, the content is synchronized to the lower part of if, this improves the execution efficiency. You do not have to synchronize the object every time you obtain it. It is only synchronized for the first time. It is unnecessary after creation.
Singleton Mode

Only new instances can be created.
Your getInstance method only returns the reference of the EagerSingleton object and does not use new. Of course it is a singleton.

Singleton mode Problems

Private is used to protect data from external changes. Without this private keyword, you can change this object as follows:
Singleton. instance = new SingLeton ();
In this case, the reference of the original Singleton is paid to the newly created instance. In this way, two Singleton instances exist in the program. With the private keyword, the instance cannot be changed externally. In addition, the default non-argument constructor declared as private is also afraid that the external class will directly use Singleton to generate the results of multiple instances, and the declared as private) the external class cannot create the instance through the constructor. You can only use the public static Singleton getInstance () method to obtain the existing Singleton.
In addition, because the declared object type is static, it will only be executed when the Singleton class is loaded by the program, that is, this statement is executed only at the first time and will not be executed again:
Private static Singleton instance = new SingLeton ();
Because it is executed only once, we can ensure that there is only one Singleton instance in the program, that is, there will be no new instance.

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.