-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNodeObserverPattern.pas
83 lines (66 loc) · 2.1 KB
/
NodeObserverPattern.pas
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
unit NodeObserverPattern;
interface
uses
classes,
ipeernodeunit,
System.Generics.Collections;
type
TMSGType = (msgtrefresh, msgtserverconnected, msgtprotocolconnected);
// Node Observer pattern
INodeObserver = interface
['{C805DD3C-5A0C-4FD3-A1D5-30DF1BC53835}']
procedure DoNotify(const msgtype: TMSGType; const aNode: INode);
end;
INodeObservable = interface
['{1ECE5AAA-F65E-4BF8-8527-75185C73A1D5}']
procedure Notify(const msgtype: TMSGType; aNode: INode);
procedure RegisterObserver(aObserver: INodeObserver);
procedure UnregisterObserver(aObserver: INodeObserver);
end;
TNodeObservable = class(TInterfacedObject, INodeObservable)
private
fObserverList: Tlist<INodeObserver>;
public
destructor Destroy; override;
procedure Notify(const msgtype: TMSGType; aNode: INode);
procedure RegisterObserver(aObserver: INodeObserver);
procedure UnregisterObserver(aObserver: INodeObserver);
end;
procedure AttachObserverToSubject(aObserver: INodeObserver; aSubject: INodeObservable);
procedure DeattachObserverFromSubject(aObserver: INodeObserver; aSubject: INodeObservable);
implementation
procedure AttachObserverToSubject(aObserver: INodeObserver; aSubject: INodeObservable);
begin
aSubject.RegisterObserver(aObserver);
end;
procedure DeattachObserverFromSubject(aObserver: INodeObserver; aSubject: INodeObservable);
begin
aSubject.UnregisterObserver(aObserver);
end;
destructor TNodeObservable.Destroy;
begin
fObserverList.free;
inherited;
end;
procedure TNodeObservable.Notify(const msgtype: TMSGType; aNode: INode);
var
aObserver: INodeObserver;
begin
for aObserver in fObserverList do
begin
aObserver.DoNotify(msgtrefresh, aNode);
end;
end;
procedure TNodeObservable.RegisterObserver(aObserver: INodeObserver);
begin
if fObserverList = nil then
fObserverList := Tlist<INodeObserver>.Create;
if fObserverList.IndexOf(aObserver) < 0 then
fObserverList.Add(aObserver);
end;
procedure TNodeObservable.UnregisterObserver(aObserver: INodeObserver);
begin
if fObserverList <> nil then
fObserverList.Remove(aObserver);
end;
end.