Delphi 设计模式:《HeadFirst设计模式》---行为模式之责任链模式

模式解说
  责任链模式是一种对象的行为模式,它将处理客户端请求的那些对象联成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。
通常使用在以下场合
  1 有多个对象可以处理一个请求,哪个对象处理该请求事先并不知道,而是在运行时自动确定;
  2 希望在不明确制定接收者的情况下,向多个对象中的一个提交请求;
  3 处理一个请求的对象集合需要动态指定时;
16.2 结构和用法
  1.抽象处理者(THandler)-定义了一个处理请求的接口。如果需要,则声明一个方法,实现对后续对象的链接;
  2.具体处理者(TConcreteHandler)-负责处理求;链接后续对象,如果它能处理该请求,则处理,如果不能,则传递给其链接对象处理;
  3.客户端(TClient)-发出请求给责任链中的具体处理对象;

代码示例:
unit Chain;

interface

type

  THandler = class
  private
    FSuccessor: THandler;
    procedure SetSuccessor(const Value: THandler);
  public
    procedure HandleRequest; virtual; abstract;
    property Successor: THandler read FSuccessor write SetSuccessor;
  end;

  TConcreteHandler1 = class(THandler)
  public
    procedure HandleRequest; override;
  end;

  TConcreteHandler2 = class(THandler)
  public
    procedure HandleRequest; override;
  end;


implementation
uses Dialogs;

{ Thandler }

procedure THandler.SetSuccessor(const Value: THandler);
begin
  FSuccessor := Value;
end;

{ TConcreteHandler2 }

procedure TConcreteHandler2.HandleRequest;
begin
  inherited;
  if Successor <> nil then
  begin
    ShowMessage(self.ClassName +  ‘将请求传递到 ‘ +  Successor.ClassName);
    Successor.HandleRequest;
  end
  else
  begin
    ShowMessage(self.ClassName + ‘ 处理了请求!‘);
  end;
end;

{ TConcreteHandler1 }

procedure TConcreteHandler1.HandleRequest;
begin
  inherited;
  if Successor <> nil then
  begin
    ShowMessage(self.ClassName +  ‘将请求传递到 ‘ +  Successor.ClassName);
    Successor.HandleRequest;
  end
  else
  begin
    ShowMessage(self.ClassName + ‘ 处理了请求!‘);
  end;
end;

end.

客户端代码



unit Main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    OtherDone: TButton;
    SelfDone: TButton;
    procedure OtherDoneClick(Sender: TObject);
    procedure SelfDoneClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses Chain;

{$R *.dfm}

procedure TForm1.OtherDoneClick(Sender: TObject);
var
  Handler1, Handler2: THandler;
begin
  Handler1 := TConcreteHandler1.Create;
  Handler2 := TConcreteHandler1.Create;
  try
    Handler1.Successor := Handler2;
    Handler1.HandleRequest;
  finally
    Handler1.Free;
    Handler2.Free;
  end;
end;

procedure TForm1.SelfDoneClick(Sender: TObject);
var
  Handler1, Handler2: THandler;
begin
  Handler1 := TConcreteHandler1.Create;
  Handler2 := TConcreteHandler1.Create;
  try
    Handler1.HandleRequest;
  finally
    Handler1.Free;
    Handler2.Free;
  end;
end;


end.

Delphi 设计模式:《HeadFirst设计模式》---行为模式之责任链模式

上一篇:C#中小数点后保留两位小数,四舍五入的函数及使用方法


下一篇:C# WinForm程序退出的方法