示例:中介者接口
说明:
(1)、定义
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
(2)、结构
clip_image002
中介者
Mediator(中介者):中介者定义一个接口用于与各同事(Colleague)对象通信。
ConcreteMediator(具体中介者):具体中介者通过协调各同事对象实现协作行为。了解并维护它的各个同事。
同事
Colleagueclass(同事类):每一个同事类都知道它的中介者对象。每一个同事对象在需与其他的同事通信的时候,与它的中介者通信。

代码:
unit uMediator;

interface

uses
    SysUtils, Dialogs;

type
    TMediator = class;

    TColleague = class
    private
        FMediator: TMediator;
    public
        constructor Create(AMediator: TMediator);
        //---
        procedure Notify();
    end;
    TConcreteColleague1 = class(TColleague)
    private
        FValue: Integer;
        procedure SetValue(const Value: Integer);
    public
        property Value: Integer read FValue write SetValue;
    end;
    TConcreteColleague2 = class(TColleague)
    private
        FValue: Integer;
        procedure SetValue(const Value: Integer);
    public
        property Value: Integer read FValue write SetValue;
    end;

    TMediator = class
    public
        procedure Changed(AColleague: TColleague); virtual; abstract;
    end;
    TConcreteMediator = class(TMediator)
    private
        FColleague1: TConcreteColleague1;
        FColleague2: TConcreteColleague1;
    public
        constructor Create;
        destructor Destroy; override;
        //---
        procedure Changed(AColleague: TColleague); override;
        procedure Calc;
    end;

procedure Test;

implementation

procedure Test;
var
    AMediator: TConcreteMediator;
begin
    AMediator := TConcreteMediator.Create;
    AMediator.Calc;
    AMediator.Free;
end;

constructor TColleague.Create(AMediator: TMediator);
begin
    FMediator := AMediator;
end;

procedure TColleague.Notify;
begin
    FMediator.Changed(self);
end;

procedure TConcreteColleague1.SetValue(const Value: Integer);
begin
    FValue := Value;
    //---
    self.Notify;
end;

procedure TConcreteColleague2.SetValue(const Value: Integer);
begin
    FValue := Value;
    //---
    self.Notify;
end;

procedure TConcreteMediator.Calc;
begin
    FColleague1.Value := 1;
end;

procedure TConcreteMediator.Changed(AColleague: TColleague);
begin
    if AColleague = FColleague1 then
        FColleague2.Value := FColleague1.Value + 2
    else if AColleague = FColleague2 then
        ShowMessage(IntToStr(FColleague2.Value));
end;

constructor TConcreteMediator.Create;
begin
    inherited;
    //---
    FColleague1 := TConcreteColleague1.Create(self);
    FColleague2 := TConcreteColleague1.Create(self);
end;

destructor TConcreteMediator.Destroy;
    //---
    procedure _Free(AColleague: TColleague);
    begin
        if AColleague <> nil then
            AColleague.Free;
    end;
begin
    _Free(FColleague1);
    _Free(FColleague2);
    //---
    inherited;
end;

end.

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐