How to use the interface with VCL classes - part 2

continue my previous research regarding the use of the interface with VCL.

How to implement identical methods with 2 or more classes?

How to use the interface with VCL classes?

I would like to have sample code to demonstrate where and how they work together. Or what is the classic advantage / use of two:

ISomething = interface ['{EFE0308B-A85D-4DF3-889C-40FBC8FE84D0}'] ... end; TSomeThing = class(TSomeVCLObject, ISomething) ... end; 
+4
source share
1 answer

Imagine that you have the classes TSomeThing and TSomeThingElse , but they do not have a common class of ancestors. As-is, you cannot pass them to a single function or call a common method. By adding a common interface to both classes, you can do both, for example:

 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; 
+5
source

Source: https://habr.com/ru/post/1390312/


All Articles