How to implement multiple inheritance in delphi?

前端 未结 9 773
一向
一向 2020-12-03 11:22

I\'m doing a full rewrite of an old library, and I\'m not sure how to handle this situation (for the sake of being understood, all hail the bike analogy):

I have the

9条回答
  •  -上瘾入骨i
    2020-12-03 11:54

    Another alternative with newer versions of Delphi is to leverage generics in a compositional model. This is particularly useful in the case where the multiple base classes (TBarA and TBarB in this example) are not accessible for modification (ie: framework or library classes). For example (note, the necessary destructor in TFoo is omitted here for brevity) :

    program Project1;
    
    uses SysUtils;
    
    {$APPTYPE CONSOLE}
    
    type    
      TFooAncestor  = class
        procedure HiThere; virtual; abstract;
      end;
      TBarA = class(TFooAncestor)
        procedure HiThere; override;
      end;
      TBarB = class(TFooAncestor)
        procedure HiThere; override;
      end;
      TFoo = class
        private
          FFooAncestor: T;
        public
          constructor Create;
          property SomeBar : T read FFooAncestor write FFooAncestor;
      end;
    
    procedure TBarA.HiThere;
    begin
      WriteLn('Hi from A');
    end;
    
    procedure TBarB.HiThere;
    begin
      WriteLn('Hi from B');
    end;
    
    constructor TFoo.Create;
    begin
      inherited;
      FFooAncestor := T.Create;
    end;
    
    var
      FooA : TFoo;
      FooB : TFoo;
    begin
      FooA := TFoo.Create;
      FooB := TFoo.Create;
      FooA.SomeBar.HiThere;
      FooB.SomeBar.HiThere;
      ReadLn;
    end.
    

提交回复
热议问题