Friday, November 14, 2008

How much of the implementation can be hidden by interfaces?

Short answer: All of it.

Consider this example:
unit uSomeManager;
interface
type
    ISomeManager = interface
    ...
    end;
function SomeManager: ISomeManager;
implementation
type
    TSomeManager = class(TInterfacedObject, ISomeManager)
    ...
    end;
var
    gSomeManager: ISomeManager;
function SomeManager: ISomeManager;
begin
    if not Assigned(gSomeManager) then
       gSomeManager := TSomeManager.Create;
    result := gSomeManager;
end;
Notice what is in the interface part of the unit. There are two things: the interface that is being defined and a global function which returns something implementing that interface. There is no class information  whatsoever. The entire implementation of this interface, including the class declaration, is in the implementation section of the unit. This prohibits others from using this class in any other way. They can't extend it, override it or instantiate another copy of it. If they want a different implementation of this interface, they have to completely re-implement it.

Whether or not this is a Good Thing is another discussion, but it does make it very clear to the user that it is intended to only have one instance of this. I find it works well for places where you might want to use a singleton, without the low-level messiness normally associated with them in Delphi.

No comments: