Template 模式之Delphi实现

基础知识 专栏收录该内容
7 篇文章 0 订阅

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
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值