Skip to content

Instantly share code, notes, and snippets.

@ccy
Created January 15, 2017 12:33
Show Gist options
  • Save ccy/ffe0812638e451a112df739b94af86cb to your computer and use it in GitHub Desktop.
Save ccy/ffe0812638e451a112df739b94af86cb to your computer and use it in GitHub Desktop.
Generic singleton
uses Patterns.Singleton.Generic;
var o1, o2: TSingleton<TStringList>;
s1, s2, s3: string;
begin
o1.Get.AddStrings(['a1', 'a2']);
s1 := o1.Get.Text; // return "a1<cr,lf>a2"
s2 := o2.Get.Text; // return "a1<cr,lf>a2"
s3 := TSingleton<TStringList>.Get.Text; // // return "a1<cr,lf>a2"
// Dispose the TStringList singleton
TSingleton<TStringList>.Dispose;
end.
unit Patterns.Singleton.Generic;
interface
type
TSingleton<T: class, constructor> = class abstract
strict private
class var FInstance: T;
public
class function Get: T;
class procedure Dispose;
end;
implementation
class function TSingleton<T>.Get: T;
begin
if not Assigned(FInstance) then
FInstance := T.Create;
Result := FInstance;
end;
class procedure TSingleton<T>.Dispose;
begin
if Assigned(Self.FInstance) then begin
FInstance.Free;
FInstance := nil;
end;
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment