unit Unit1;
{By 月夜风筝,icc}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
btn1: TButton;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
//关于两数A,B的二元运算,返回同类型
TCallBackFunc = function (const A, B: Integer): Integer;
var
Form1: TForm1;
implementation
{$R *.dfm}
{下面的四个函数给出了支持回调接口的四种运算,即:加、减、除、平方和
注:从回接口 “TCallBackFunc” 可以看出,它是关于二元整型的运算符,返回整型
这几个函数都符合接口规范,因此可被随意回调
这几个函数可以看作是“数据运算插件”,它们的开发可由多人共同进行
这几个函数充当了具体的回调执行代码
}
function Add(const A, B: Integer): Integer;
begin
Result := A + B;
end;
function Minus(const A, B: Integer): Integer;
begin
Result := A - B;
end;
function Multi(const A, B: Integer): Integer;
begin
Result := A * B;
end;
function Square(const A, B: Integer): Integer;
begin
Result := A * A + B * B;
end;
{这里定义了回调,比较重要的接口}
function Calc(const OP: TCallBackFunc
const X, Y: Integer): string;
begin
Result := IntToStr(OP(X, Y));{这里的“OP”就是回调的定义之地}
{ 更典型的写法可能是如下形式,VCL中有大量类似代码
Result := -1;
if Assigned(OP) then
Result := IntToStr(OP(X, Y));
}
end;
procedure TForm1.btn1Click(Sender: TObject);
const
A = 2;
B = 3;
var
s : string;
begin
s := Calc(Add, A, B)
{这里激活了回调,以下同}
s := Format('"Add"
of %0:d and %1:d is : %2:s', [A, B, S]);
ShowMessage(s);
s := Calc(Minus, A, B);
s := Format('"Minus"
of %0:d and %1:d is : %2:s', [A, B, S]);
ShowMessage(s);
s := Calc(Square, A, B);
s := Format('"Square Plus"
of %0:d and %1:d is : %2:s', [A, B, S]);
ShowMessage(s);
end;
end.