[fpc-devel] delegate objects

Leonardo M. Ram� martinrame at yahoo.com
Tue Jan 30 19:39:07 CET 2007


> Is there a way do delegate such methods on classes using Object 
Pascal ?
> If so, how would you do it ?

Yes, delegates are called "Events" in Object Pascal.

Here a simple example:

program EventExample;

uses
  SysUtils, Classes;

type
  { define the event type }
  TOnCalc = procedure (APercent: Integer) of object;

  { class that triggers the event }
  TCalculator = class
  private
    FOnCalc: TOnCalc; 
  public
    procedure Calculate(A, B: Integer);
    property OnCalc: TOnCalc read FOnCalc write FOnCalc;
  end;

  { class that uses the event }
  TPresenter = class
  public
    procedure PresenterOnCalc(APercent: Integer);  // <--- this is the 
delegated method
    procedure ShowCalc;
  end;

implementation

{ TCalculator }
procedure TCalculator.Calculate(A, B: Integer);
begin
  Writeln(A + B);
  { Execute the event if assigned from outside this class }
  if Assigned(OnCalc) then
    OnCalc(10); // 10 is the percent calculated at this moment
end;

{ TPresenter }
procedure TPresenter.ShowCalc;
var
  lCalculator: TCalculator;
begin
  lCalculator := TCalculator.Create;
  lCalculator.OnCalc := PresenterOnCalc; // <-- assign the delegate
  lCalculator.Free;
end;

procedure TPresenter.PresenterOnCalc(APercent: Integer);
begin
  Writeln('Calculated at this moment: ' + APercent + '%');
end;

end.

Leonardo M. Ramé
http://leonardorame.blogspot.com


 
____________________________________________________________________________________
Finding fabulous fares is fun.  
Let Yahoo! FareChase search your favorite travel sites to find flight and hotel bargains.
http://farechase.yahoo.com/promo-generic-14795097



More information about the fpc-devel mailing list