如何用观察者替换多事件(Spring4D)

时间:2016-06-22 11:45:08

标签: delphi design-patterns observer-pattern spring4d

我上课时有2个事件:OnConnect和OnDisconnect:

type
    TEvent = reference to procedure;
    TConnection = class
    private
        fOnConnect: TEvent;
        fOnDisconnect: TEvent;
    public
        procedure SomeBehavior(aChoice: Boolean);
        property OnConnect: TEvent read fOnConnect write fOnConnect;
        property OnDisconnect: TEvent read fOnDisconnect write fOnDisconnect;
    end;

implementation

{ TConnection }

procedure TConnection.SomeBehavior(aChoice: Boolean);
begin
    if aChoice then
        fOnConnect
    else
        fOnDisconnect;
    //im not cheacking Assign(Events) to make example simple
end;

现在我想做同样的事情,但更多的对象风格。 我的意思是使用String4D的接口和观察者模式。我做了这个:

interface

uses
    Spring.DesignPatterns;

type
    IObserver = interface
        procedure ReactToConnect(aText: String);
        procedure ReactToDisconnect(aTimeoutInMs: Integer);
    end;

    IConnection<T> = interface(IObservable<IObserver>)
        procedure SomeBehavior(aChoice: Boolean);
    end;

implementation

uses
    System.SysUtils;

type
    TConnection = class(TObservable<IObserver>, IConnection<IObserver>)
    public
        procedure SomeBehavior(aChoice: Boolean);
    end;

{ TConnection }

procedure TConnection.SomeBehavior(aChoice: Boolean);
var
    procOnConnect: TProc<IObserver>;
    procOnDisconnect: TProc<IObserver>; // what if i want no parameters?
    someText: String;
    someNumber: Integer;
begin
    someText := RandomText;
    procOnConnect := procedure(aObserver: IObserver)
                      begin
                          aObserver.ReactToConnect(someText);
                      end;
    someNumber := RandomInt;
    procOnDisconnect := procedure(aObserver: IObserver)
                         begin
                            aObserver.ReactToDisconnect(someNumber);
                         end;

    if aChoice then
        Self.NotifyListeners(procOnConnect)
    else
        Self.NotifyListeners(procOnDisconnect);

end;
我正在做这个时间,只是想问一下它的正确方法吗?或者我在这里做一些异端的思考?

0 个答案:

没有答案