Embarcadero Delphi Defining and implementing an interface


Example

An interface is declared like a class, but without access modifiers (public, private, ...). Also, no definitions are allowed, so variables and constants can't be used.

Interfaces should always have an Unique Identifier, which can be generated by pressing Ctrl + Shift + G.

IRepository = interface
    ['{AFCFCE96-2EC2-4AE4-8E23-D4C4FF6BBD01}']
    function  SaveKeyValuePair(aKey: Integer; aValue: string): Boolean;
end;

To implement an interface, the name of the interface must be added behind the base class. Also, the class should be a descendant of TInterfacedObject (this is important for the lifetime management).

TDatabaseRepository = class(TInterfacedObject, IRepository)
    function  SaveKeyValuePair(aKey: Integer; aValue: string): Boolean;
end;

When a class implements an interface, it must include all methods and functions declared in the interface, else it won't compile.

One thing worth noting is that access modifiers don't have any influence, if the caller works with the interface. For example all functions of the interface can be implemented as strict private members, but can still be called from another class if an instance of the interface is used.