[fpc-devel] delegate objects

ik idokan at gmail.com
Tue Jan 30 21:12:12 CET 2007


Hi,

Thank you for the example.
I will study it more on the weekend, when I'll have more time to learn it ..

Ido

On 1/30/07, Leonardo M. Ramé <martinrame at yahoo.com> wrote:
> > 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
> _______________________________________________
> fpc-devel maillist  -  fpc-devel at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-devel
>


-- 
http://ik.homelinux.org/


More information about the fpc-devel mailing list