When developing a VCL or program, you will need to use an object event to trigger many related object methods. That is, the example of 1. n.
In Java, interface-related mode programming can also be implemented in Delphi, But I have encapsulated it through a tnotifier class. When other classes are to be implemented in the future, you can directly implements tnotifier In the attribute.
unit Unit2;interface
uses
Classes;
type
INotifier = interface;
INotifier = interface(IInterface)
['{0DEBB550-E67D-4CB1-8B16-A7690200D4DF}']
procedure Register(Event:TNotifyEvent);
procedure Unregister(Event:TNotifyEvent);
procedure DoNotify;
end;
TNotifier=class(TInterfacedPersistent,INotifier)
private
FOwner: TObject;
FList: TList;
protected
public
procedure Register(Event:TNotifyEvent);
procedure Unregister(Event:TNotifyEvent);
procedure DoNotify;
procedure Clear;
constructor Create(aOwner:TObject);
destructor Destory;
end;
implementation
uses
SysUtils;
type
PNotifyEvent = ^TNotifyEvent;
{ TNotifier }
procedure TNotifier.Register(Event:TNotifyEvent);
var
p: PNotifyEvent;
begin
New(p);
p^ := Event;
FList.Add(p);
end;
procedure TNotifier.Clear;
var
I: Integer;
begin
for I := 0 to FList.Count - 1 do // Iterate
begin
Dispose(FList.Items[I]);
end; // for
FList.Clear;
end;
constructor TNotifier.Create(aOwner:TObject);
begin
FOwner := aOwner;
FList := TList.Create;
end;
destructor TNotifier.Destory;
begin
Clear;
FreeAndNil(FList);
end;
procedure TNotifier.DoNotify;
var
I: Integer;
p:PNotifyEvent;
begin
for I := 0 to FList.Count - 1 do // Iterate
begin
p:= FList.Items[I];
try
p^(FOwner);
finally
// free resources
end; // try/finally
end; // for
end;
procedure TNotifier.Unregister(Event:TNotifyEvent);
var
I: Integer;
p,p1:PNotifyEvent;
begin
New(p1);
try
p1^ := Event;
for I := FList.Count - 1 downto 0 do // Iterate
begin
p:= FList.Items[I];
if PInteger(p)^ = PInteger(p1)^ then
begin
Dispose(p);
FList.Remove(p);
end;
end;
finally
Dispose(p1);
end; // try/finally // for
end;
end.
//TData class implements INotifier
unit Unit3;
interface
uses
Unit2;
type
TData = class(TObject,INotifier)
private
FNotifier: TNotifier;
function GetNotifier: INotifier;
public
constructor Create;
destructor Destroy;
property Notifier: INotifier read GetNotifier implements INotifier;
end;
implementation
constructor TData.Create;
begin
inherited Create;
FNotifier := TNotifier.Create(self);
end;
destructor TData.Destroy;
begin
FNotifier.Free;
inherited Destroy;
end;
function TData.GetNotifier: INotifier;
begin
result := FNotifier;
end;
end.
Source code download