【Delphi】UEventBus

unit UEventBus;

interface

uses
    System.Classes;

type
    IEventBus = interface(IUnknown)
        procedure Notify(information: TObject);
    end;



    TEventBus = class(TObject)
    private
        subscribers: TInterfaceList;
    public
        constructor Create;
        destructor Destroy; override;
        procedure Attach(subscriber: IEventBus);
        procedure Detach(subscriber: IEventBus);
        procedure Push(information: TObject);
    end;

implementation

constructor TEventBus.Create;
begin
    subscribers := TInterfaceList.Create;
end;

destructor TEventBus.Destroy;
begin
    subscribers.Destroy;
    inherited;
end;

procedure TEventBus.Attach(subscriber: IEventBus);
begin
    if subscribers.IndexOf(subscriber) < 0 then begin
        subscribers.Add(subscriber);
    end;
end;

procedure TEventBus.Detach(subscriber: IEventBus);
begin
    if subscribers.IndexOf(subscriber) > -1 then begin
        subscribers.Remove(subscriber);
    end;
end;

procedure TEventBus.Push(information: TObject);
var
    i: Integer;
begin
    with subscribers do begin
        for i := 0 to Count - 1 do begin
            IEventBus(Items[i]).Notify(information);
        end;
    end;
end;

end.


上一篇:RACSignal的Subscription深入分析


下一篇:JDK9新特性 Reactive Stream 响应式流