Есть цепочка объектов. Одно звено выполняет одни операции, другое – другие.
program ChainsOfResponsibilities;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
uChainsOfResponsibilities in 'uChainsOfResponsibilities.pas';
var
d: TDirector;
m: TManager;
w: TWorker;
p: TPurchase;
begin
d := TDirector.Create();
m := TManager.Create();
w := TWorker.Create();
p := TPurchase.Create(5);
try
w.SetNextApprover(m);
m.SetNextApprover(d);
w.ProcessRequest(p); // trying to buy
Readln;
finally
d.Free();
m.Free();
w.Free();
p.Free();
end;
end.
Шаблон “цепочки обязанностей”
unit uChainsOfResponsibilities;
interface
uses
System.SysUtils;
type
TPurchase = class
FPrice: Double;
public
constructor Create(aPrice: Double);
property Price: Double read FPrice;
end;
TApprover = class
FNextApprover: TApprover;
public
procedure SetNextApprover(aApprover: TApprover);
procedure ProcessRequest(aPurchase: TPurchase); virtual; abstract;
end;
TDirector = class(TApprover)
public
procedure ProcessRequest(aPurchase: TPurchase); override;
end;
TManager = class(TApprover)
public
procedure ProcessRequest(aPurchase: TPurchase); override;
end;
TWorker = class(TApprover)
public
procedure ProcessRequest(aPurchase: TPurchase); override;
end;
implementation
{ TPurchase }
constructor TPurchase.Create(aPrice: Double);
begin
FPrice := aPrice;
end;
{ TApprover }
procedure TApprover.SetNextApprover(aApprover: TApprover);
begin
FNextApprover := aApprover;
end;
{ TDirector }
procedure TDirector.ProcessRequest(aPurchase: TPurchase);
begin
if aPurchase.Price < 10 then
Writeln('Director: approved')
else
Writeln('Director: too expensive');
end;
{ TManager }
procedure TManager.ProcessRequest(aPurchase: TPurchase);
begin
if aPurchase.Price < 10 then
begin
Writeln('Manager: approved');
FNextApprover.ProcessRequest(aPurchase);
end
else
Writeln('Manage: too expensive');
end;
{ TWorker }
procedure TWorker.ProcessRequest(aPurchase: TPurchase);
begin
if aPurchase.Price < 10 then
begin
Writeln('Worker: approved');
FNextApprover.ProcessRequest(aPurchase);
end
else
Writeln('Worker: too expensive');
end;
end.