CSDN博客

img largewang

Template 模式之Delphi实现

发表于2003/3/3 18:08:00  699人阅读

unit Tpl_meth;

{
Design pattern example -
some simple classes using the Template Method pattern.
}
interface

type
  TAbstractTemplateClass = class(TObject)
  protected
    function Algorithm_StepA: Integer; virtual; abstract;
    function Algorithm_StepB: Integer; virtual; abstract;
    function Algorithm_StepC: Integer; virtual; abstract;
  public
    function Algorithm: Integer;
  end;

  TConcreteClassA = class(TAbstractTemplateClass)
  protected
    function Algorithm_StepA: Integer; override;
    function Algorithm_StepB: Integer; override;
    function Algorithm_StepC: Integer; override;
  end;

  TConcreteClassB = class(TAbstractTemplateClass)
  protected
    function Algorithm_StepA: Integer; override;
    function Algorithm_StepB: Integer; override;
    function Algorithm_StepC: Integer; override;
  end;

implementation

function TAbstractTemplateClass.Algorithm: Integer;
begin
  Result := Algorithm_StepA +
            Algorithm_StepB +
            Algorithm_StepC;
end;

function TConcreteClassA.Algorithm_StepA: Integer;
begin
  Result := 1;
end;

function TConcreteClassA.Algorithm_StepB: Integer;
begin
  Result := 2;
end;

function TConcreteClassA.Algorithm_StepC: Integer;
begin
  Result := 3;
end;

function TConcreteClassB.Algorithm_StepA: Integer;
begin
  Result := 4;
end;

function TConcreteClassB.Algorithm_StepB: Integer;
begin
  Result := 5;
end;

function TConcreteClassB.Algorithm_StepC: Integer;
begin
  Result := 6;
end;

end.

 

/////////////////////////////////////////////////////////////////////////////////

 

unit Unit1;

interface

uses
  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

uses tpl_meth;

procedure TForm1.Button1Click(Sender: TObject);
var
  AnAbstractObject: TAbstractTemplateClass;
begin
  AnAbstractObject := TConcreteClassA.Create;
  try
    ShowMessage('Algorithm Result = ' + Inttostr(AnAbstractObject.Algorithm));
  finally
    AnAbstractObject.Destroy;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  AnAbstractObject: TAbstractTemplateClass;
begin
  AnAbstractObject := TConcreteClassB.Create;
  try
    ShowMessage('Algorithm Result = ' + Inttostr(AnAbstractObject.Algorithm));
  finally
    AnAbstractObject.Destroy;
  end;
end;

end.

0 0

相关博文

我的热门文章

img
取 消
img