[fpc-devel] delegate objects

Leonardo M. Ram� martinrame at yahoo.com
Mon Jan 29 12:45:08 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


 
____________________________________________________________________________________
Don't pick lemons.
See all the new 2007 cars at Yahoo! Autos.
http://autos.yahoo.com/new_cars.html 



More information about the fpc-devel mailing list