Practical Design Mode-singleton Mode

Source: Internet
Author: User
1. What is Singleton 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 provide global access points.

2. Use of Singleton

The example in the textbook is very simple. To implement a singleton class, you only need three points:

  • Define Private Static members
  • Privatization Construction Method
  • Provides public static factory methods

The typical code is:

public class Singleton {private static Singleton instance;private Singleton(){}public static Singleton getInstance(){if (instance==null){instance=new Singleton();}return instance;}}

But we often have to face more complex real-world problems.

. Use all static members

Sometimes we can see that all the member variables of a singleton are of the static type. In this case, we recommend that you delete the constructor and static factory methods directly as a tool class. Because this class no longer requires objects, why should we do this?

2. No privatization of Construction Methods

If the constructor method is not privatized, it means that the client can freely construct a new instance through new Singleton (). This is against the intention of using the singleton mode. It is better to delete the static factory method, abandon the singleton requirement. If there is a reason for a class to be either a singleton or multiple examples, I think it should be carefully designed.

2. parameters required for static factory methods

We often see the following constructor:

Public staticSingleton getinstance (context)

If the construction of an instance requires parameters, it means that passing different parameters will affect the status of the single instance. For example, let's look at such a piece of code.

public class Singleton {private static Singleton instance;private Object value;private Singleton(Object value){this.value=value;}public static Singleton getInstance(Object value){if (instance==null){instance=new Singleton(value);}return instance;}public void fun(){//value.doSomething();}}

Singleton is used for calling somewhere in the program. getinstance (obja ). fun (); Singleton is used in another place. getinstance (objb ). fun (); apparently, the same Singleton instance experienced unexpected behavior during runtime. This is inconsistent with the expected controllability when designing a Singleton, and you cannot predict the real behavior when using value next time.

2. 4. derived subclass

If you need to use a singleton in the inheritance tree, you only need to adjust the base class constructor from private to protected, but there are many problems. This article has discussed this and skipped it here.

In short, if a static factory method is implemented in the base class, it is bound to be dependent on the subclass, that is, the parent class depends on the abnormal situation of the subclass. If the static factory method is implemented in the subclass, the creation of the parent class cannot be restricted in the whole design, that is, the implementation that violates the design intent may occur. We recommend that you do not assign a single instance type.

. Multithreading

Since there is only one instance during the software runtime, it is inevitable to handle the mutex problem because the client call time cannot be limited.

Let's take a look at the mutex processing of the static factory method. The typical code is:

public static Singleton getInstance(){if (instance==null){synchronized (Singleton.class) {if (instance==null){instance=new Singleton();}}}return instance;}

This Code not only protects the construction of a unique instance, but also prevents unnecessary mutex processing when the instance is retrieved multiple times after the construction to improve the running efficiency, is a recommended implementation method.

Let's look at the mutex problem of other members of the class. This is the same as other classes. We need to be careful with the impact of multi-thread access.

. Memory recovery

The memory of a single instance is also worth noting. After a single instance is created, the static variable instance will hold a memory reference, and due to its static nature, the memory will continue to be occupied during the running of the program and cannot be recycled by GC. Therefore, memory-sensitive programs should reduce the use of Singleton instances, or properly handle memory recovery issues.

3. Summary

In short, although the singleton looks beautiful, there are still so many technical points that require careful consideration and proper decision-making. The use of Singleton is not as simple as we have seen in textbooks.

-- Welcome to reprint, please indicate the source of --

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: 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.