Next, we can define a class implementing it: I type

TGetValue = class (TSingletonlmplementation, IGetValue) private fValue: Integer; publ ic constructor Create (Value: Integer = 0); function GetValue: Integer; procedure SetValue (Value: Integer); end ;

Things start to get interesting in the definition of a generic class limited to types that implement the given interface: type

TInftClass <T: IGetVa1ue> = class private vali, va12: T; // or IGetValue publ ic procedure Seti (vai: T); procedure Set2 (vai: t); function GetMin: Integer; function GetAverage: Integer; procedure IncreaseByTen; end ;

Notice that in the code of the generic methods of this class we can write, for example:

function TInftCiass<T>.GetMin: Integer; begi n

Result := min (vail.GetVaiue, va12.GetVaiue); end ;

procedure TInftCiass<T>.IncreaseByTen; begi n vail.SetVaiue (vail.GetVaiue + 10); va12.Vaiue := va12.Vaiue + 10; end ;

With all these definitions, we can now use the generic class as follows:

procedure TFormIntfConstraint.btnVa1ueCiick(

Sender: TObject); var iCiass: TInftCiass<TGetVaiue>; begi n iCiass := TInftCiass<TGetVaiue>.Create; try iCiass.Setl (TGetVaiue.Create (5)); iCiass.Set2 (TGetVaiue.Create (25)); Log ('Average: ' + IntToStr (iCiass.GetAverage)); iCiass.IncreaseByTen;

Log ('Min: ' + IntToStr (iCiass.GetMin)); Marco Cantù, Delphi 2009 Handbook fi nal ly iClass.va11.Free; iClass.va12.Free; iClass.Free;



To show the flexibility of this generic class, I've created another totally different implementation for the interface:

TButtonValue = class (TButton, IGetValue) publ ic function GetValue: Integer; procedure SetValue (Value: Integer); class function MakeTButtonValue (Owner: TComponent; Parent: TWinControl): TButtonValue;


function TButtonValue.GetValue: Integer; begi n

procedure TButtonVa1ue.SetVa1ue(Va1ue: Integer); begi n

The class function (not listed in the book) creates a button within a Parent control in a random position and is used in the following sample code:

procedure TFormIntfConstraint.btnVa1ueButtonC1ick(

Sender: TObject); var iC1ass: TInftC1ass<TButtonVa1ue>; begi n iC1ass := TInftC1ass<TButtonVa1ue>.Create; try iC1ass.Set1 (TButtonVa1ue.MakeTButtonVa1ue (

se1f, Scro11Box1)); iC1ass.Set2 (TButtonVa1ue.MakeTButtonVa1ue (

se1f, Scro11Box1)); Log ('Average: ' + IntToStr (iC1ass.GetAverage)); Log ('Min: ' + IntToStr (iC1ass.GetMin)); iC1ass.IncreaseByTen;

Log ('New Average: ' + IntToStr (iC1ass.GetAverage)); fi na11y iC1ass.Free;



Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment