views:

120

answers:

1

I have a class TDevice. Some devices will have a cellular module. So I create an Interface IIMEI. Others devices will have an Ethernet Module. So I create an Interface IMacAddress.

So, I'd like to create another class that is a child of TDevice and implements IIMEI or IMacAddress or both.

Is it possible in Delphi?

+2  A: 

The easiest option is to derive TDevice from TInterfaced Object and just extend your descendants with the additional methods. Beware of interface reference counting, though, otherwise you will end up with lots of unexpected access violations.

Alternatively you can write a wrapper object that descends from TInterfacedObject and delegates the implementation of the interfaces to TDevice descendants. In that case reference counting will be less of a problem.

TMacAddressWrapper = class(TInterfacedObject, IMacAddress)
private
  FDevice: TDevice;
  property Device: TDevice read FDevice implements IMacAddress;
public
  constructor Create(_Device: TDevice);
end;

constructor TMacAddressWrapper.Create(_Device: TDevice);
begin
  inherited Create;
  FDevice := _Device;
end;
dummzeuch
+1. But I don't think that your alternative solution does really help with ref counting - the problems are just different, as one would have to make sure that fDevice is not freed as long as the wrapper ref count is > 0. IMHO using interfaces is best done when full advantage of automatic lifetime management is taken, hybrid solutions tend to break sooner or later.
mghie