is singleton design pattern thread safe(20分)

  • 主题发起人 主题发起人 yyanghhong
  • 开始时间 开始时间
Y

yyanghhong

Unregistered / Unconfirmed
GUEST, unregistred user!
The singleton design pattern defines a variation to the normal Object - Class relation.
The variation is that the class creates only one object for all the application,
and returns that one object any time someone requests an object of that class
eg
Type
TSingleton = class(TObject)
Private
Procedure Dispose;
protected
Procedure Init;
Virtual;
Procedure BeforeDestroy;
Virtual;
Public
class Function NewInstance: TObject;
Override;
Procedure FreeInstance;
Override;
end;

TInterfacedSingleton = class(TInterfacedObject, IUnknown)
Private
Procedure Dispose;
protected
Procedure Init;
Virtual;
Public
class Function NewInstance: TObject;
Override;
Procedure FreeInstance;
Override;
Function _AddRef: Integer;
stdcall;
Function _Release: Integer;
stdcall;
end;


i want to use this pattern in multi thread appliction.
so i am wondering that if it is thread safe,
 
Yes and No.
Because it is only a class framework, you will call many others functions or
use many other objects to get your class implemented, it depends on what kind
of operation will be used in your class implementation.
e.g. If you use TList from the VCL object hierarchy, it is not thread-safe.
You have to use TThreadList, the thread-safe version instead.
 
Thanks your suggestion, you mean this pattern is nothing about multithread, i have to
use Semaphore, Mutex or CriticalSection to deal with multithread, could you tell me
what is the advantage of the singleton design pattern
 
接受答案了.
 

Similar threads

后退
顶部