在Delphi中具有继承性的流畅接口 [英] Fluent interface with inheritance in Delphi
问题描述
我有以下流利的接口声明和实现该接口的类:
I have following fluent interface declaration and class that implements that interface:
type
IDocWriter = interface
['{8CB5799A-14B1-4287-92FD-41561B237560}']
function Open: IDocWriter;
function Close: IDocWriter;
function Add(const s: string): IDocWriter;
function SaveToStream(Stream: TStream): IDocWriter;
end;
TDocWriter = class(TInterfacedObject, IDocWriter)
public
function Open: IDocWriter;
function Close: IDocWriter;
function Add(const s: string): IDocWriter;
function SaveToStream(Stream: TStream): IDocWriter;
end;
{ TDocWriter }
function TDocWriter.Open: IDocWriter;
begin
Result := Self;
// DoOpen
end;
function TDocWriter.Close: IDocWriter;
begin
Result := Self;
// DoClose
end;
function TDocWriter.Add(const s: string): IDocWriter;
begin
Result := Self;
// DoAdd
end;
function TDocWriter.SaveToStream(Stream: TStream): IDocWriter;
begin
Result := Self;
// DoSaveToStream
end;
我可以使用以下代码:
var
Stream: TStream;
...
TDocWriter.Create
.Open
.Add('abc')
.Close
.SaveToStream(Stream);
我必须通过添加 SaveToString
功能。
I have to extend above interface by adding SaveToString
function.
我不想将该方法添加到原始的 IDocWriter
接口中,因为它不是所有接口的有效方法实现。所以我已经完成了
I don't want to add that method to original IDocWriter
interface because it is not valid method for all interface implementations. So I have done following
type
IStrDocWriter = interface(IDocWriter)
['{177A0D1A-156A-4606-B594-E6D20818CE51}']
function SaveToString: string;
end;
TStrDocWriter = class(TDocWriter, IStrDocWriter)
public
function SaveToString: string;
end;
{ TStrDocWriter }
function TStrDocWriter.SaveToString: string;
begin
Result := 'DoSaveToString';
end;
为了使用 IStrDocWriter
接口编写代码
var
Writer: IDocWriter;
s: string;
Writer := TStrDocWriter.Create
.Open
.Add('abc')
.Close;
s := (Writer as IStrDocWriter).SaveToString;
但是我希望能够使用它而无需声明 Writer
变量,类似于以下代码(当然不能编译)
But I would like to be able to use it without the need to declare Writer
variable, something like following code (which, of course, cannot be compiled)
s := TStrDocWriter.Create
.Open
.Add('abc')
.Close
.SaveToString; // Undeclared identifier SaveToString
有什么方法可以实现?
Is there any way to achieve that?
可以对上述接口和类进行任何更改(显然,将这两个接口合并为一个)。
Any kind of changes to above interfaces and classes are acceptable (except, obviously, merging those two interfaces into one).
推荐答案
您可以这样写:
s := (TStrDocWriter.Create
.Open
.Add('abc')
.Close as IStrDocWriter)
.SaveToString;
不,不是很好。流利的接口和继承这两个习惯用法根本就不混在一起。
No, not very nice is it. These two idioms, fluent interfaces and inheritance, simply do not mix.
这篇关于在Delphi中具有继承性的流畅接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!