Dal*_*kar 5 delphi fluent-interface delphi-xe4
我有以下流利的接口声明和实现该接口的类:
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;
Run Code Online (Sandbox Code Playgroud)
而且我可以像上面这样使用上面的代码:
var
Stream: TStream;
...
TDocWriter.Create
.Open
.Add('abc')
.Close
.SaveToStream(Stream);
Run Code Online (Sandbox Code Playgroud)
我必须通过添加SaveToString功能来扩展接口。
我不想将该方法添加到原始IDocWriter接口,因为它不是所有接口实现的有效方法。所以我做了以下
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;
Run Code Online (Sandbox Code Playgroud)
为了使用IStrDocWriter接口,我必须编写代码
var
Writer: IDocWriter;
s: string;
Writer := TStrDocWriter.Create
.Open
.Add('abc')
.Close;
s := (Writer as IStrDocWriter).SaveToString;
Run Code Online (Sandbox Code Playgroud)
但是我希望能够在不需要声明Writer变量的情况下使用它,就像下面的代码(当然,不能编译)
s := TStrDocWriter.Create
.Open
.Add('abc')
.Close
.SaveToString; // Undeclared identifier SaveToString
Run Code Online (Sandbox Code Playgroud)
有什么办法可以实现?
可以对上述接口和类进行任何形式的更改(显然,将这两个接口合并为一个除外)。
| 归档时间: |
|
| 查看次数: |
537 次 |
| 最近记录: |