What is Singleton:
Singleton mode ( Singleton ) Is a common software design model. When this mode is applied, the class of the singleton object must ensure that only one instance exists. In many cases, the whole system only needs to have one global object, which is conducive to coordinating the overall behavior of the system. The idea of implementing the singleton mode is: A class can return an object and a reference ( Always the same ) And a method to obtain the instance (must be a static method, usually used Getinstance This name); when we call this method, if the reference held by the class is not null, this reference is returned, if the reference of the class persistence is null, create an instance of the class and assign the instance reference to the reference of the class persistence. At the same time, we also define the constructor of the class as a private method.CodeYou cannot instantiate the object of this class by calling the constructor of this class. You can only obtain the unique instance of this class through the static method provided by this class. [ Wikipedia ] Delphi Singleton application in source code:
VaR
Fclipboard: tclipboard;
Function Clipboard: tclipboard;
Begin
If Fclipboard = Nil Then
Fclipboard: = tclipboard. Create;
Result: = fclipboard;
End ;
Question:
The above code is not thread-safe. Hypothesis A Call functions first Clipboard , Local variable Fclipboard Will be instantiated first. Before the instance is fully created, if B Also try to call the Function Clipboard , Then it will also Fclipboard . Because the variable Fclipboard The pointer is still null. Thus A , B Create Tclipboard ! One of them becomes a memory leak. Such leaks are often sent when building a function takes a long time. How can I change the above Code to thread-safe? In fact, it can be solved by adding a critical section.
VaR
Fclipboard: tclipboard;
Gclipboardlocker: trtlcriticalsection;
Function Clipboard: tclipboard;
Begin
If Fclipboard = Nil Then
Begin
Entercriticalsection (gclipboardlocker );
Try
If Fclipboard = Nil Then
Fclipboard: = tclipboard. Create;
Finally
Leavecriticalsection (gclipboardlocker );
End ;
End ;
Result: = fclipboard;
End ;
Initialization
Initializecriticalsection (gclipboardlocker );
Finalization
Deletecriticalsection (gclipboardlocker );
End.
conclusion:
the singleton mode is simple but not simple. After development is extended to multiple threads, more problems may occur. A singleton is a global variable. We recommend that you do not abuse it. Otherwise, the hierarchy of the software will be damaged.