-
-
Save azzahrah/33355da07e88a0a4c4d5d3639df4ecb9 to your computer and use it in GitHub Desktop.
Generic Singleton Pattern in Delphi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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