I'm trying to understand TVirtualInterface class.
{$APPTYPE CONSOLE}
uses
SysUtils, Rtti;
type
ISpecificInterface = interface(IInvokable)
['{281D8B97-397E-430A-895A-9CA4E1F5FB5F}']
procedure SpecificProcedure;
end;
procedure AProcedure(Method: TRttiMethod; const Args: TArray<TValue>;
out Result: TValue);
begin
Writeln(Method.ToString);
end;
var
ISpecificInterfaceInstance: ISpecificInterface;
begin
ISpecificInterfaceInstance := TVirtualInterface.Create
(TypeInfo(ISpecificInterface), AProcedure) as ISpecificInterface;
ISpecificInterfaceInstance.SpecificProcedure;
end. // TVirtualInterface ref. counter is decremented
What's the benefit of implement an interface at runtime ?
What is the use of space ?
Code maintainability: Interfaces helps to reduce coupling and therefore allow you to easily interchange implementations for the same concept without the underlying code being affected.
Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.
If, as a programmer, you code against the implementation then as soon as it changes your code stops working. So think of the benefits of the interface this way: it hides the things you do not need to know making the object simpler to use. it provides the contract of how the object will behave so you can depend on that.
The purpose of interfaces is to allow the computer to enforce these properties and to know that an object of TYPE T (whatever the interface is ) must have functions called X,Y,Z, etc.
The description is here
Provides functionality for remote procedure call marshaling...
There are many ways of using this but they all have in common that because of the fact that you are using an interface the caller side does not care how the implementation looks like - if its an actual class that was implementing the interface at compiletime or if you dynamically implemented it at runtime via TVirtualInterface
or other ways as long as it behaves according to the interface contract.
When this was first introduced in XE2 I wrote an article about it and its possible usages. As was mentioned in the comments this in fact enabled us to implement mocking frameworks in a very easy way just by declaring generic mock types that internally creates an interface proxy that handles the calls specified on the mock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With