How to use Interface with VCL Classes - Part 2 [closed]

对着背影说爱祢 提交于 2019-12-07 08:19:07

问题


continue with my previous investigation regarding the use of Interface with VCL.

How to implement identical methods with 2 and more Classes?

How to use Interface with VCL Classes?

I would like to have a code example to demonstrate where and how the two work together. Or what is the classic benefit/usage of the two:

ISomething = interface
['{EFE0308B-A85D-4DF3-889C-40FBC8FE84D0}']
...
end;

TSomeThing = class(TSomeVCLObject, ISomething)
...
end;

回答1:


Imagine you have TSomeThing and TSomeThingElse classes, but they do not have a common ancestor class. As-is, you would not be able to pass them to the same function, or call a common method on them. By adding a shared interface to both classes, you can do both, eg:

type
  ISomething = interface 
  ['{EFE0308B-A85D-4DF3-889C-40FBC8FE84D0}'] 
  public
    procedure DoSomething;
  end; 

  TSomeThing = class(TSomeVCLObject, ISomething) 
    ... 
    procedure DoSomething;
  end; 

  TSomeThingElse = class(TSomeOtherVCLObject, ISomething) 
    ... 
    procedure DoSomething;
  end; 

procedure TSomeThing.DoSomething;
begin
  ...
end; 

procedure TSomeThingElse.DoSomething;
begin
  ...
end; 

procedure DoSomething(Intf: ISomething);
begin
  Intf.DoSomething;
end;

procedure Test;
var
  O1: TSomeThing;
  O2: TSomeThingElse;
  Intf: ISomething;
begin
  O1 := TSomeThing.Create(nil);
  O2 := TSomeThingElse.Create(nil);
  ...
  if Supports(O1, ISomething, Intf) then
  begin
    Intf.DoSomething;
    DoSomething(Intf);
  end;
  if Supports(O2, ISomething, Intf) then
  begin
    Intf.DoSomething;
    DoSomething(Intf);
  end;
  ...
  O1.Free;
  O2.Free;
end;


来源:https://stackoverflow.com/questions/8810052/how-to-use-interface-with-vcl-classes-part-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!