Created
January 15, 2017 12:33
-
-
Save ccy/ffe0812638e451a112df739b94af86cb to your computer and use it in GitHub Desktop.
Generic singleton
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
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. |
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 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