Объекты связаны друг с другом через посредника. Так называемая слабая связанность.
program MediatorPattern;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
uMediator in 'uMediator.pas';
var
Stas: TColleague;
Masha: TColleague;
chat: TMediator;
begin
chat := TMediator.Create();
chat.AddParticipant(TColleague.Create(1, 'Stas'));
chat.AddParticipant(TColleague.Create(2, 'Masha'));
Stas := chat.Colleague[0];
Masha := chat.Colleague[1];
try
Stas.Send('Привет, Маша, пойдем гулять?', Masha);
Masha.Send('Привет, Стас, конечно!', Stas);
ReadLn;
finally
chat.Free();
end;
end.
Паттерн “Медиатор”
unit uMediator;
interface
uses
System.SysUtils, System.generics.Collections;
type
TMediator = class;
TColleague = class
FId: integer;
FName: string;
FMediator: TMediator;
public
constructor Create(aId: integer; aName: string);
destructor Destroy; override;
procedure Send(aMsg: string; aCoallegue: TColleague);
procedure Notify(aMsg: string; aSenderCoallegue: TColleague);
property Id: integer read FId;
property Name: string read FName;
property Mediator: TMediator read FMediator write FMediator;
end;
TMediator = class
FColleagues: TObjectList<TColleague>;
private
function GetColleague(aIndex: integer): TColleague;
public
constructor Create();
destructor Destroy; override;
procedure Send(sSenderCoallegue: TColleague; aMsg: string; aColleague: TColleague);
procedure AddParticipant(aColleague: TColleague);
property Colleague[aIndex: integer]: TColleague read GetColleague;
end;
implementation
{ TMediator }
procedure TMediator.AddParticipant(aColleague: TColleague);
begin
if aColleague <> nil then
FColleagues.Add(aColleague);
aColleague.Mediator := Self;
end;
constructor TMediator.Create;
begin
FColleagues := TObjectList<TColleague>.Create(true);
end;
destructor TMediator.Destroy;
begin
FColleagues.Free();
inherited;
end;
function TMediator.GetColleague(aIndex: integer): TColleague;
begin
Result := FColleagues[aIndex];
end;
procedure TMediator.Send(sSenderCoallegue: TColleague; aMsg: string; aColleague: TColleague);
var
i: integer;
colleague: TColleague;
begin
for i := 0 to FColleagues.Count - 1 do
begin
colleague := FColleagues[i];
if colleague.Id = FColleagues[i].Id then
begin
FColleagues[i].Notify(aMsg, sSenderCoallegue);
Break;
end;
end;
end;
{ TColleague }
constructor TColleague.Create(aId: integer; aName: string);
begin
FMediator := TMediator.Create();
FId := aId;
FName := aName;
end;
destructor TColleague.Destroy;
begin
FMediator.Free();
inherited;
end;
procedure TColleague.Notify(aMsg: string; aSenderCoallegue: TColleague);
begin
WriteLn(aSenderCoallegue.Name + ': ' + aMsg);
end;
procedure TColleague.Send(aMsg: string; aCoallegue: TColleague);
begin
FMediator.Send(Self, aMsg, aCoallegue);
end;
end.