示例:职责链接口
说明:
(1)、定义
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
(2)、结构
对象:
* Handler:处理对象。定义一个处理请求的接口。(可选)实现后继链。
* ConcreteHandler:具体处理对象。处理它所负责的请求。可访问它的后继者。如果可处理该请求,就处理之;否则将该请求转发给它的后继者。
客户端:
Client:向链上的具体处理者(ConcreteHandler)对象提交请求。
代码:
unit uChainOfResponsibility;
interface
uses
Dialogs;
type
THandler = class
private
FSuccessor: THandler;
public
constructor Create(const ASuccessor: THandler = nil);
//---
procedure HandleRequest; virtual;
end;
TConcreteHandler1 = class(THandler)
public
procedure HandleRequest; override;
end;
TConcreteHandler2 = class(THandler)
public
procedure HandleRequest; override;
end;
implementation
constructor THandler.Create(const ASuccessor: THandler = nil);
begin
FSuccessor := ASuccessor;
end;
procedure THandler.HandleRequest;
begin
if assigned(FSuccessor) then
FSuccessor.HandleRequest
end;
procedure TConcreteHandler1.HandleRequest;
begin
ShowMessage('ConcreteHandler1');
//---
inherited;
end;
procedure TConcreteHandler2.HandleRequest;
begin
ShowMessage('ConcreteHandler2');
//---
inherited;
end;
end.
procedure TForm1.Button1Click(Sender: TObject);
var
AHandler1: TConcreteHandler1;
AHandler2: TConcreteHandler2;
begin
AHandler2 := TConcreteHandler2.Create;
AHandler1 := TConcreteHandler1.Create(AHandler2);
try
AHandler1.HandleRequest;
finally
AHandler1.Free;
AHandler2.Free;
end;
end;