Delphi 实现 事件分发机制
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
PMethod = ^TMethod;
TMutliEvent = procedure(const Value ,value2: string) of object;
TMultiEventClass = class
private
fMultiEventHandlers : TList;
public
constructor Create;
destructor Destroy; override;
procedure AddMultiEvent(const Value: TMutliEvent);
procedure RemoveMultiEvent(const Value: TMutliEvent);
procedure FireMultiEvent;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
procedure Handler1(const value,value2 : string);
procedure Handler2(const value,value2 : string);
procedure Handler3(const value,value2 : string);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TMultiEventClass }
constructor TMultiEventClass.Create;
begin
inherited Create;
fMultiEventHandlers := TList.Create;
end;
destructor TMultiEventClass.Destroy;
var
cnt: Integer;
begin
for cnt := 0 to -1 + fMultiEventHandlers.Count do
Dispose(fMultiEventHandlers[cnt]);
fMultiEventHandlers.Free;
inherited;
end;
procedure TMultiEventClass.RemoveMultiEvent(const Value: TMutliEvent);
var
cnt: Integer;
begin
for cnt := 0 to -1 + fMultiEventHandlers.Count do
begin
if (TMethod(Value).Code = TMethod(fMultiEventHandlers[cnt]^).Code) and
(TMethod(Value).Data = TMethod(fMultiEventHandlers[cnt]^).Data) then
begin
Dispose(fMultiEventHandlers[cnt]);
fMultiEventHandlers.Delete(cnt);
Break;
end;
end;
end;
procedure TMultiEventClass.AddMultiEvent(const Value: TMutliEvent);
var
h: PMethod;
begin
h := New(PMethod);
h^.Code := TMethod(Value).Code;
h^.Data := TMethod(Value).Data;
fMultiEventHandlers.Add(h);
end;
procedure TMultiEventClass.FireMultiEvent;
var
cnt: Integer;
msg : string;
begin
for cnt := 0 to -1 + fMultiEventHandlers.Count do
begin
msg := Format('%d/%d %s',[1 + cnt, fMultiEventHandlers.Count, 'fired!']);
TMutliEvent(fMultiEventHandlers[cnt]^)(msg,'TEST');
end;
end;
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
test : TMultiEventClass;
begin
test := TMultiEventClass.Create;
try
test.AddMultiEvent(Handler1);
test.AddMultiEvent(Handler2);
// test.RemoveMultiEvent(Handler1);
test.AddMultiEvent(Handler3);
test.FireMultiEvent;
finally
test.Free;
end;
end;
procedure TForm1.Handler1(const value,value2: string);
begin
ShowMessage(value2 +'h1:' + value);
end;
procedure TForm1.Handler2(const value,value2: string);
begin
ShowMessage(value2 + 'h2:' + value);
end;
procedure TForm1.Handler3(const value,value2: string);
begin
ShowMessage(value2 + 'h3:' + value);
end;
end.