Free interface with inheritance in Delphi

I have a current interface declaration and a class that implements this 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;

And I can use the code above:

var
  Stream: TStream;
  ...
  TDocWriter.Create
    .Open
    .Add('abc')
    .Close
    .SaveToStream(Stream);

I need to expand the interface by adding a function SaveToString.

I do not want to add this method to the original interface IDocWriter, because this is an invalid method for all implementations of the interface. So I did the 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;

To use the interface IStrDocWriter, I need to write code

var
  Writer: IDocWriter;
  s: string;

  Writer := TStrDocWriter.Create
    .Open
    .Add('abc')
    .Close;
  s := (Writer as IStrDocWriter).SaveToString;

But I would like to be able to use it without having to declare a variable Writer, something like the 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 this?

Any changes in interfaces and classes are acceptable (except, obviously, combining these two interfaces into one).

+4
1

:

s := (TStrDocWriter.Create
    .Open
    .Add('abc')
    .Close as IStrDocWriter)
    .SaveToString; 

, . , .

+4

All Articles