Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Under what circumstances can Singleton mode be used

Shulou Source: shulou.com Published: 2022-06-01 03:38:37 10月04日 Update

This article mainly introduces the relevant knowledge of "under what circumstances can you use Singleton mode". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "under what circumstances you can use Singleton mode" can help you solve the problem.

Applicability

Singleton mode can be used in the following cases

When a class can have only one instance and the customer can access it from a well-known access point.

There is something wrong with the translation of this sentence, let's look at the original English text:

There must be exactly one instance of a class, and it must be accessible

To clients from a well-known access point.

The author believes that it should be translated like this: when the class can only have one instance and the instance is required to be accessible through a clear and concise access point.

When this unique instance should be extensible by subclassing, and the customer should be able to use an extended instance without changing the code.

English original text

When the sole instance should be extensible by subclassing, and clients

Should be able to use an extended instance without modifying their code.

The author's translation: when the only instance needs to be extended through a subclass and the customer is required to use the instance of the extension without modifying the code.

structure

This is probably the simplest class diagram in Design patterns. But even so, the diagram can be simplified: only two static members are really necessary.

Participant

Singleton

-defines an Instance operation that allows customers to access its unique instance. Instance is a class operation (that is, a class method in Smalltalk and a static member function in C++).

When the word class operation is relative to the instance operation, C++ is the static member function.

-may be responsible for creating its own unique instance.

It is also possible to use instances defined by the implementation (such as global variables).

Collaboration

Customers can only access one instance of Singleton through the Instance operation of Singleton.

This is the end of the introduction to "under what circumstances can you use Singleton mode"? thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Instance pattern customer situation member knowledge static code author function original text subclass method industry problem Category English different practical concise Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Redmi Apple Linux MySQL