Delphi 单例双重检查锁定

Delphi Singleton double check locking

我想实现一个单例临界区,以保护跨多个 类 的一些代码(不要再问了.​​..)。我已经看到 Delphi Singleton Pattern and Aquire Singleton class Instance Multithread 但这些正在使用全局函数来 return 单例,我不希望那样。所以,我实现了自己的版本:

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.

它工作正常,但我不喜欢 initialization\finalization 部分。有没有其他方法可以不使用全局变量、函数来实现?

如果您想将所有必要的代码封装在 class 的命名空间中,那么您可以分别用 class constructor and a class destructor 替换 initializationfinalization 部分.这些将从单元 initializationfinalization 过程中隐式调用。