Although the Singleton mode is good, do not abuse it.

Source: Internet
Author: User
Speaking of SingleTon, I believe that SingleTon is a well-known design pattern as long as you know the design pattern. This is a well-known design model, but it is the most abused design model. This article will discuss the abuse of SingleTon. First, GoF considers problems in a pure OO field. Therefore, many problems in other fields have not been taken into consideration,

When it comes to object-oriented design patterns, many people can say a few common patterns at will, but have you ever thought about the design patterns? even beginners can say at least SingleTon and Factory Method. So, is it okay to use the design model as needed?

The answer to this question must be no (you have not accepted exam-oriented education for so many years ). However, I personally observe that there are definitely not a few abuse of design patterns. In addition, the simpler the model, the more likely it will be abused.

Start with SingleTon, the simplest mode.

Speaking of SingleTon, I believe that SingleTon is a well-known design pattern as long as you know the design pattern. This is a well-known design model, but it is the most abused design model. This article will discuss the abuse of SingleTon.

Thread security is a problem

First, GoF considers problems in a pure OO field. Therefore, many problems in other fields have not been taken into consideration (in fact, it is not suitable to be discussed together ), however, programmers have to deal with problems in more fields (the most common is the concurrency field ). This is why SingleTon in GoF is so simple, but when writing SingleTon in Java or. net, you need to pay attention to the root cause of the lock problem. Regarding whether SingleTon is thread-safe, I tend to break down the problem into two parts:

  1. Is SingleTon thread safe?
  2. Whether the SingleTon instance is thread safe

For the first question, I believe everyone is very clear about the security of the double check lock in the famous Java. if you still have any questions, please refer to the relevant materials, this article will not be repeated. Here, we will focus on the second question: whether the SingleTon instance is thread-safe.

If you carefully read msdn, msdn writes the following sentence in most classes: Public static (Shared in Visual Basic) members of this type are thread safe. any instance members are not guaranteed to be thread safe.

In the msdn Chinese version, this type of public static (Shared in Visual Basic) members are thread-safe. However, it cannot guarantee that any instance member is thread-safe.

In the class library provided by ms, all static members are written as thread-safe, while most instance members are treated as loose threads, developers are required to handle the thread insecurity of instance members during development (I believe the Java Class Library is similar ).

So what problems does SingleTon use in multi-threaded programs? First, SingleTon only allows one class to have only one instance. Here is a simple reasoning:

  1. In this program, you can only use this unique instance whenever you need an instance of this class.
  2. No matter which thread of this program, you can only use this unique instance when you need an instance of this class.
  3. No matter what concurrency occurs in this program, you can only use this unique instance when you need an instance of this class.
  4. No matter what concurrency occurs in this program, when you need to call a member of this class instance, you can only use members of this unique instance.
  5. No matter what concurrency occurs in this program, to ensure the program is thread safe, when you need to call a member of this class instance, only members of this unique instance can be used, and thread security must be ensured.
  6. No matter what kind of concurrency occurs in this program, to ensure the program is thread-safe, when you need to call a member of this class instance, if this member is not thread-safe, when using this unique instance member, correct thread synchronization is required.

No problem found. who needs to ensure the thread security of SingleTon instance members?

  • Option A: SingleTon instances ensure that all members are thread-safe.
  • Option B: SingleTon instances do not guarantee thread security. please add locks when using them.

If you select A, check the SingleTon code to see if the heap is used. check whether any calls to the heap are thread-safe or synchronized.

If you select B, check all the code that uses SingleTon to see if it has been reliably synchronized by a thread (for example, Lock the SingleTon object, as a result, the entire thread is insecure (but how many people who write Web pages will pay attention to the resources that need to be synchronized by threads ?).

Is there any option C? Yes. if it is a class library, it declares that the program is thread insecure. ensure thread security before use (for example, the famous Stas in COM ); if it is an application, we will tell the customer that the thread is not secure and any problems may occur. at the beginning of the contract, we did not say that we should ensure thread security (the customer will be crazy ).

Why SingleTon?

I wonder if you have ever thought about why to use SingleTon for this type. Most of the answers I see are resource saving and global status, and fixed algorithm interface adaptation (not to rule out better answers ).

First, we will discuss the issue of resource saving. First, we do not need to question whether the new instance must save resources (CPU and memory) than the new instance, but if we want to ensure thread security, it seems that we have to consider it again.

If the implementation method of the SingleTon instance ensures thread security (only the objects in the stack and parameters are used, and the referenced objects are read-only), thread security is zero. If the implementation method involves synchronization such as Lock, what is the probability of conflict? if the probability of conflict is high enough, most of the time threads will enter the waiting state, resulting in a large amount of time resources and CPU resources. Even if the probability of conflict is low, because the Lock needs to synchronize the Cache and memory, it also takes some extra cost (the time cost of synchronizing the Cache ).

Speaking of this, I still think the SingleTon with Lock will save resources than the new instance? Maybe not. who saves the resources or analyzes specific problems? without Profiling, who knows the results?

As for the global status, you can avoid using the global status whenever possible. if you need to use the global status, there is really no good solution. However, we recommend that SingleTon, which is used as the global state, ensure the thread security of all members (otherwise, a small error of a team member may cause a global state error ).

The third method of fixed algorithm interface adaptation is my SingleTon usage. The requirements are as follows:

  1. Fixed algorithms
  2. The algorithm does not exist. all changes come from parameters, and thread security can be ensured without thread synchronization.
  3. The receiver must comply with an interface (generic)

If the first point is not met, it cannot exist as SingleTon. The second is to ensure the performance advantages of SingleTon. The third point is the necessity of SingleTon in the OO standpoint. Otherwise, why not use static methods.

The three points may be abstract. here is an example of the actual point:

public class PersonNameComparer    : IComparer
 
  {    public int Compare(Person x, Person y)    {        if (x == y)            return 0;        if (x == null)            return -1;        if (y == null)            return 1;        return string.Compare(x.name, y.name);    }}
 

First, the algorithm is fixed, that is, compare the names of two people. if there is no second algorithm, it is also the responsibility of other classes. Second, there is no state. only two parameters x and y are used, no thread synchronization; third, because IComparer is required for sorting Therefore, you cannot use static methods (assuming you cannot use delegation ).

Therefore, if this type is SingleTon, it will be reasonable (of course there is no problem with SingleTon here ).

Remarks

N years ago, when I went to an interview with a company, an interviewer asked me if my database connection could be SingleTon. I said no, and many questions would be introduced. as a result, the interviewer was not satisfied.

N months ago, I interviewed someone about where the design pattern was used. for example, I made a WebService proxy class into SingleTon in a Web project. Ah, SingleTon, SingleTon, is the biggest pitfall for GoF to introduce OO.

Address of this article: http://www.nowamagic.net/librarys/veda/detail/921,welcome.

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.