-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelper.Singleton.pas
More file actions
97 lines (76 loc) · 1.96 KB
/
Copy pathHelper.Singleton.pas
File metadata and controls
97 lines (76 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
{*******************************************************}
{ YAGE: Yet Another Global Encoder }
{ Unit: Helper.Singleton }
{ Copyright(c) 2021 Alexey Anisimov }
{ Contact email: softlight@ya.ru }
{*******************************************************}
unit Helper.Singleton;
{$MODE delphiunicode}
interface
type
TSingleton = class(TObject)
private
class procedure RegisterInstance(aInstance: TSingleton);
procedure UnRegisterInstance;
class function FindInstance: TSingleton;
protected
constructor Create; virtual;
public
class function NewInstance: TObject; override;
procedure BeforeDestruction; override;
constructor GetInstance;
end;
implementation
uses
Classes, Types, Contnrs;
var
SingletonList : TObjectList;
{ TSingleton }
class procedure TSingleton.RegisterInstance(aInstance: TSingleton);
begin
SingletonList.Add(aInstance);
end;
procedure TSingleton.UnRegisterInstance;
begin
SingletonList.Extract(Self);
end;
class function TSingleton.FindInstance: TSingleton;
var
i: Integer;
begin
Result := nil;
for i := 0 to SingletonList.Count - 1 do
if SingletonList[i].ClassType = Self then
begin
Result := TSingleton(SingletonList[i]);
Break;
end;
end;
constructor TSingleton.Create;
begin
inherited Create;
end;
class function TSingleton.NewInstance: TObject;
begin
Result := FindInstance;
if Result = nil then
begin
Result := inherited NewInstance;
TSingleton(Result).Create;
RegisterInstance(TSingleton(Result));
end;
end;
procedure TSingleton.BeforeDestruction;
begin
UnregisterInstance;
inherited BeforeDestruction;
end;
constructor TSingleton.GetInstance;
begin
inherited Create;
end;
initialization
SingletonList := TObjectList.Create(True);
finalization
SingletonList.Free;
end.