我想实现一个单例关键部分,以保护跨多个类的某些代码(不要再问了……)。我见过Delphi Singleton Pattern和Aquire Singleton class Instance Multithread,但是它们使用了全局函数来返回单例,我不希望这样。因此,我已经实现了自己的版本:
unit SynchronizationHandler;
interface
uses
SyncObjs;
type
TSynchronizationHandler = class
strict private
FCriticalSection: TCriticalSection;
private
class var FSingletonCriticalSection: TCriticalSection;
class var FInstance: TSynchronizationHandler;
public
constructor Create;
destructor Destroy; override;
procedure Lock;
procedure Release;
class function Instance: TSynchronizationHandler;
end;
implementation
{ TSynchronizationHandler }
constructor TSynchronizationHandler.Create;
begin
FCriticalSection := TCriticalSection.Create;
end;
destructor TSynchronizationHandler.Destroy;
begin
FCriticalSection.Destroy;
end;
{Doublec check locking for this singletone}
class function TSynchronizationHandler.Instance: TSynchronizationHandler;
begin
if not Assigned(FInstance) then
begin
FSingletonCriticalSection.Acquire;
try
if not Assigned(FInstance) then
FInstance := TSynchronizationHandler.Create;
finally
FSingletonCriticalSection.Release;
end;
end;
Result := FInstance;
end;
procedure TSynchronizationHandler.Lock;
begin
FCriticalSection.Acquire;
end;
procedure TSynchronizationHandler.Release;
begin
FCriticalSection.Release;
end;
initialization
TSynchronizationHandler.FSingletonCriticalSection := TCriticalSection.Create;
finalization
if Assigned(TSynchronizationHandler.FInstance) then
TSynchronizationHandler.Instance.Free;
TSynchronizationHandler.FSingletonCriticalSection.Free;
end.
它正在工作,但是我不喜欢初始化\完成部分。还有其他方法可以在不使用全局变量,函数的情况下完成此任务吗?
答案 0 :(得分:4)
如果要将所有必需的代码封装在类的名称空间中,则可以将initialization
和finalization
部分替换为class constructor和class destructor,分别。这些将从单元initialization
和finalization
过程中隐式调用。