Warum nicht die Variable auch noch mit in die Klasse?
Delphi-Quellcode:
type
TSingleton = class sealed
private
class var Singleton : TSingleton;
constructor Create;
public
procedure Tuwas;
destructor Destroy; override;
class function GetInstance : TSingleton;
end;
Und den Destructor würde ich noch absichern, damit keiner die Instanz von extern freigeben kann.
Delphi-Quellcode:
TSingleton = class sealed
private
class var Singleton : TSingleton;
class var AllowFree : Boolean;
constructor Create;
public
procedure Tuwas;
destructor Destroy; override;
procedure FreeInstance; override;
class function GetInstance : TSingleton;
end;
class function TSingleton.GetInstance: TSingleton;
var
S: TSingleton;
begin
if not Assigned(Singleton) then
begin
S := TSingleton.Create;
if Assigned(InterlockedCompareExchangePointer(Pointer(Singleton), Pointer(S), nil)) then
S.Free;
end;
Result := Singleton;
end;
procedure TSingleton.FreeInstance;
begin
if AllowFree then
inherited FreeInstance;
end;
finalization
TSingleton.AllowFree := True;
TSingleton.Singleton.Free;