Singleton mode is one of the 23 most commonly used design patterns. The single mode shields object initialization, so you can easily obtain the object instead of initializing it every time. Because of its ease of use and ease of use, a class in singleton mode is used in many cases. This article emphasizes that, despite its ease of use, the singleton mode cannot be abused. When using it, you also need to carefully consider it.
1. Singleton mode is one of the manifestations of cache.
After a single object is initialized, it will stay in the memory during the program running. Since it is a cache, you need to consider which objects need to be cached and which objects do not. After all, the system resources are limited and it is impossible to cache all the content. If the object is not used too frequently, you need to consider that the value of the cached object is not worth it.
2. if the singleton mode is used, it means that the reference of other modules to this module is always 1, and the reference of one to many or many to many cannot be reached, that is, the use of objects is limited. The caller can only use this object repeatedly. can you ensure that the object is always in a predetermined state? If not, do not use Singleton mode. If the object is stateless, it is more suitable to provide the singleton mode. In terms of system expansion, if you need to use an object repeatedly, you should provide another Provider class or Cache class. In this class, Cache an object, and provides external interfaces to access this object.
3. The Singleton mode limits the extension of objects. What if a class is extended into a singleton mode? I'm afraid it's awkward. In my experience, in an application or framework, you should avoid using Singleton classes except for the following types of roles.
- Provides auxiliary data classes
- Classes that are frequently used and stateless and do not need to be synchronized
- Classes for creating objects, such as providers, Cache, Builder, and Factory
- Configuration operation