Skip to content

Instantly share code, notes, and snippets.

@drgarcia1986
Created April 2, 2014 14:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save drgarcia1986/9935480 to your computer and use it in GitHub Desktop.
Save drgarcia1986/9935480 to your computer and use it in GitHub Desktop.
Generic Singleton Pattern in Delphi
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
uSingletonGeneric in 'uSingletonGeneric.pas',
uMyClass in 'uMyClass.pas';
var
oSingleton1 : TMyClass;
oSingleton2 : TMyClass;
oNoSingleton : TMyClass;
begin
ReportMemoryLeaksOnShutdown := true;
oNoSingleton := TMyClass.Create;
oSingleton1 := TMyClassSingleton.GetInstance();
oSingleton2 := TMyClassSingleton.GetInstance();
try
try
oNoSingleton.Value := 1;
oSingleton1.Value := 2;
oSingleton2.Value := 3;
Writeln(Format('NoSingleton: %d | Singleton1: %d | Singleton2: %d',[oNoSingleton.Value,
oSingleton1.Value,
oSingleton2.Value]));
Readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
finally
oNoSingleton.free;
end;
end.
{
###OUTPUT###
NoSingleton: 1 | Singleton1: 3 | Singleton2: 3
}
unit uMyClass;
interface
uses uSingletonGeneric;
type
TMyClass = class
strict private
FValue : integer;
public
property Value : Integer read FValue write FValue;
end;
TMyClassSingleton = TSingleton<TMyClass>;
implementation
initialization
finalization
TMyClassSingleton.ReleaseInstance();
end.
unit uSingletonGeneric;
interface
type
TSingleton<T: class, constructor> = class
strict private
class var FInstance : T;
public
class function GetInstance(): T;
class procedure ReleaseInstance();
end;
implementation
{ TSingleton<T> }
class function TSingleton<T>.GetInstance: T;
begin
if not Assigned(Self.FInstance) then
Self.FInstance := T.Create();
Result := Self.FInstance;
end;
class procedure TSingleton<T>.ReleaseInstance;
begin
if Assigned(Self.FInstance) then
Self.FInstance.Free;
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment