Apa itu anonymous method? Anonymous method adalah procedure atau function yang tak bernama. Coba lihat contoh pemanggilan method di Delphi 2006 berikut ini:
unit unitMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls;
type
TStringMethod = function (input: String): String of object;
TForm1 = class(TForm)
edInput: TEdit;
lblLowerCase: TLabel;
lblUpperCase: TLabel;
lblLowerCase2: TLabel;
lblUpperCase2: TLabel;
procedure edInputChange(Sender: TObject);
private
{ Private declarations }
function LowerMethod(input: String): String;
function UpperMethod(input: String): String;
function ManipulateString(customStringMethod: TStringMethod; input: String): String; overload;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.edInputChange(Sender: TObject);
begin
lblLowerCase2.Caption := ManipulateString(Self.LowerMethod,
edInput.Text);
lblUpperCase2.Caption := ManipulateString(Self.UpperMethod,
edInput.Text);
end;
function TForm1.LowerMethod(input: String): String;
begin
Result := LowerCase(input);
end;
function TForm1.ManipulateString(customStringMethod: TStringMethod;
input: String): String;
begin
Result := customStringMethod(input);
end;
function TForm1.UpperMethod(input: String): String;
begin
Result := UpperCase(input);
end;
end.
Sekarang kita bandingkan dengan penerapan anonymous method untuk pemanggilan lower dan upper functionnya:
unit unitMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TStringFunction = reference to function(s: String): String;
TForm1 = class(TForm)
edInput: TEdit;
lblLowerCase: TLabel;
lblUpperCase: TLabel;
procedure edInputChange(Sender: TObject);
private
{ Private declarations }
function ManipulateString(customStringFunction: TStringFunction; input: String): String;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.edInputChange(Sender: TObject);
begin
lblLowerCase.Caption := ManipulateString(
function(input: String): String
begin
Result := LowerCase(input);
end,
edInput.Text);
lblUpperCase.Caption := ManipulateString(
function(input: String): String
begin
Result := UpperCase(input);
end,
edInput.Text);
end;
function TForm1.ManipulateString(customStringFunction: TStringFunction;
input: String): String;
begin
Result := customStringFunction(input);
end;
end.
Sekarang kita bisa mempassing parameter berupa fungsi tak bernama yang instan sekali pakai. Jadi kalau memang kita perlu implementasi fungsi yang mungkin tidak dipakai di tempat lain, kenapa tidak membuat instance anonymous method saja? Lebih fleksibel, lebih ringkas, dan lebih mudah!