我的类定义如下:
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;
示例代码:
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;
那么,假设您有一个表单,上面有三个按钮。一个“狗”按钮,一个“猫”按钮和一个“处理队列”按钮。当您按下“狗”或“猫”按钮时,相关类被添加到数组中充当队列。然后,当您按下“处理队列”按钮时,程序遍历数组,创建相应类的对象,然后调用该类中实现的接口方法。请记住上面的示例代码,如何才能实现这一点?
显然,简单的方法是将类名作为字符串添加到字符串数组中,然后在OnProcessQueueButtonPressed过程中使用if语句,例如:
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;
我尽力避免这种情况,因为每次我添加新的类时,都需要记得为新类添加一个
if
块。