Delphi Singleton double check locking

Viewed 303

I want to implement a singleton critical section in order to protect some code across several classes(don't ask further...). I've seen Delphi Singleton Pattern and Aquire Singleton class Instance Multithread but these are using a global function to return the singleton and I don't want that. So, I've implemented my own version:

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.

It's working but I don't like the initialization\finalization part. Is there any other way to accomplish this without using global variables, functions?

1 Answers

If you want to encapsulate all the necessary code inside the namespace of the class then you can replace the initialization and finalization sections with a class constructor and a class destructor, respectively. These will be called implicitly from the unit initialization and finalization procedures.

Related