What's the benefit of implement interface at runtime?
Asked Answered
C

2

6

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 ?

Camilacamile answered 20/4, 2016 at 7:21 Comment(1)
The docs say: "The main application area of TVirtualInterface is SOAP messaging.The SOAP server declares a service with specific functions. The WSDL importer creates a Delphi interface that "mirrors" the server service. On the client side, a class is created at run time that implements the Delphi interface that reflects the server service (TVirtualInterface). When a method of this class is called, the call is packed in a SOAP envelope, sent to the server, decoded, and the result is sent back to the Delphi client."Significative
K
5

The description is here

Provides functionality for remote procedure call marshaling...

Kith answered 20/4, 2016 at 7:54 Comment(1)
Exactly. From the example above, AProcedure method can serialize the parameters, send them to a remote server, wait for results and return them to the caller. In other words, TVirtualInterface instance can act as a proxy for the caller.Jeremie
F
4

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.

Feudalize answered 20/4, 2016 at 8:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.