Delphiのimplementsの機能がよくわからなかったので、試してみた。
まずはインターフェースを定義する。
//インターフェース
IMyInterface = interface
['{EF7A4A8E-F6E4-44CB-B68D-6FB8EA2AB5C7}']
procedure DoSomething;
end;
次にインターフェースを継承した実装クラスを定義する。
ここではTAggregatedObjectクラスを継承した。
こうすることで、コントローラオブジェクトの参照カウントを共有することができる。
今回の例では、TInterfacedObjectを継承しても違いはない。
TMyInterfaceImpl = class(TAggregatedObject, IMyInterface)
procedure DoSomething;
end;
DoSomethingメソッドの実装。
procedure TMyInterfaceImpl.DoSomething;
begin
WriteLn('TMyInterfaceImpl.DoSomething');
end;
委譲するクラスを定義する。
//委譲するクラス
TMyClass = class(TInterfacedObject, IMyInterface)
private
//移譲先
FMyInterface: IMyInterface;
public
constructor Create;
//IMyInterfaceの処理をFMyInterfaceに委譲する
property MyInterface: IMyInterface read FMyInterface
implements IMyInterface;
end;
TMyClassはIMyInterfaceを継承しているが、DoSomethingメソッドを持たない。
IMyInterfaceの処理はFMyInterfaceに委譲している。
TMyClassのコンストラクタの実装。
constructor TMyClass.Create;
begin
FMyInterface := TMyInterfaceImpl.Create(Self);
end;
最後にサンプルコード。
var
MyClass: TMyClass;
MyInterface: IMyInterface;
begin
MyClass := TMyClass.Create;
MyInterface := MyClass as IMyInterface;
MyInterface.DoSomething; //=> TMyInterfaceImpl.DoSomething
MyClassのDoSomethingメソッドは呼べない(コンパイルエラーになる)。
MyClassをIMyInterfaceにキャストした時にFMyInterfaceに委譲されるようだ。
implementsを使うと、対象のインターフェースにキャストした時に指定したオブジェクトに委譲されるようだ。