Use virtual constructor until reset to initial state

I have no experience with virtual constructors that are available in Delphi. I am considering using virtual ctors in a class hierarchy to reset an instance to an initial state like this:

A = class
end;
B = class(A)
end;
C = class(B)
end;

FooA = class
    a_ : A;
    constructor Create(inst : A); overload;
    constructor Create; overload; virtual; abstract;
    destructor Destroy; override;
    function Bar : A;
end;

FooB = class(FooA)
    b_ : B;
    constructor Create; override;
    constructor Create(inst : B); overload;
end;

FooC = class(FooB)
// ...
end;

{ FooA }
constructor FooA.Create(inst: A);
begin
    inherited Create;
    a_ := inst;
end;

destructor FooA.Destroy;
begin
    FreeAndNil(a_);
    inherited;
end;

function FooA.Bar : A;
begin
    Result := a_;
    a_ := nil;

    // here comes the magic
    Self.Create;
end;

{ FooB }
constructor FooB.Create;
begin
    b_ := B.Create;
    inherited Create(b_);
end;

constructor FooB.Create(inst: B);
begin
    inherited Create(inst);
    b_ := inst;
end;
{ FooC } // ...

var
    fc : FooA;
    baz : A;
begin
    fc := FooC.Create;
    baz := fc.Bar;
    WriteLn(baz.ClassName);
    FreeAndNil(baz);
    FreeAndNil(fc);
    ReadLn;
end.

Are there any problems / traps in this project? A simple example works like a charm, but I feel a little complicated call constructors (which don't create anything).

Edit:

I decided to transfer initialization to a method in a protected area with a meaningful name, which makes me feel better; -)

FooA = class
strict private
    a_ : A;
strict protected
    procedure SetInst; overload; virtual; abstract;
    procedure SetInst(i : A); overload;
public
    constructor Create;
    destructor Destroy; override;
    function Foo : A;
end;
+3
source share
2 answers

. , . , , .

, . Delphi; , (, , ), - , - . . Bar A , , .

+3

, , - . , , - : < factory.

, , factory , . , , factory.

, DFM. , TComponent, . object, , , TComponent.Create . , .

+1

Source: https://habr.com/ru/post/1778974/


All Articles