My class definitions are :
TAnimal = class(TInterfacedObject)
public
constructor Create; overload;
constructor Create(param : string); overload;
end;
IAnimal = interface
procedure DoSomething;
end;
TDog = class(TAnimal, IAnimal)
public
procedure DoSomething;
end;
TCat = class(TAnimal, IAnimal)
public
procedure DoSomething;
end;
Example code :
procedure TForm1.DogButtonPressed(Sender: TObject);
var
myDog : TDog;
I : Integer;
begin
myDog := TDog.Create('123');
I := Length(myQueue);
SetLength(myQueue, I+1);
myQueue[I] := TDog; //Probably not the way to do it...??
end;
procedure TForm1.CatButtonPressed(Sender: TObject);
var
myCat : TCat;
I : Integer;
begin
myCat := TCat.Create('123');
I := Length(myQueue);
SetLength(myQueue, I+1);
myQueue[I] := TCat; //Probably not the way to do it...??
end;
procedure TForm1.OnProcessQueueButtonPressed(Sender: TObject);
var
MyInterface : IAnimal; //Interface variable
I : Integer;
begin
for I := Low(myQueue) to High(myQueue) do
begin
MyInterface := myQueue[I].Create('123'); //Create instance of relevant class
MyInterface.DoSomething;
end;
end;
So, let's say you have a form with three buttons on it. A "Dog" button, a "Cat" button and a "Process Queue" button. When you press either the "Dog" button or the "Cat" button, the relevant class is added to an array to act as a queue. When you then press the "Process Queue" button, the program steps through the array, creates an object of the relevant class, and then calls an interface method that is implemented in that class. Keeping my example code above in mind, how can this be accomplished?
The easy way would obviously be to add the class names as a string to an array of string and then use an if statement in the OnProcessQueueButtonPressed procedure, eg :
procedure TForm1.OnProcessQueueButtonPressed(Sender: TObject);
var
MyInterface : IAnimal; //Interface variable
I : Integer;
begin
for I := Low(myQueue) to High(myQueue) do
begin
if myQueue[I] = 'TDog' then
MyInterface := TDog.Create('123');
if myQueue[I] = 'TCat' then
MyInterface := TCat.Create('123');
MyInterface.DoSomething;
end;
end;
I am trying to avoid this, because every time I add a new class I will have to remember to add an if block for the new class.