How to implement multiple inheritance in delphi?

前端 未结 9 796
一向
一向 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条回答
  •  孤街浪徒
    2020-12-03 11:42

    you can try this way, if you do not want to repeat the code several times and want a decoupled code.

    type
       TForm1 = class(TForm)
        btnTest: TButton;
        procedure btnTestClick(Sender: TObject);
       private
          { Private declarations }
       public
          { Public declarations }
       end;
    
       TBike = class
       end;
    
       IBikeWheel = interface
          procedure DoBikeWheel;
       end;
    
       TBikeWheel = class(TInterfacedObject, IBikeWheel)
       public
          procedure DoBikeWheel;
       end;
    
       IBikeWheelFront = interface
          procedure DoBikeWheelFront;
       end;
    
       TBikeWheelFront = class(TInterfacedObject, IBikeWheelFront)
       public
          procedure DoBikeWheelFront;
       end;
    
       IBikeWheelBack = interface
       end;
    
       TBikeWheelBack = class(TInterfacedObject, IBikeWheelBack)
       end;
    
       TBikeWheelFrontXYZ = class(TInterfacedObject, IBikeWheel, IBikeWheelFront)
       private
          FIBikeWheel: IBikeWheel;
          FBikeWheelFront: IBikeWheelFront;
       public
          constructor Create();
          property BikeWheel: IBikeWheel read FIBikeWheel implements IBikeWheel;
          property BikeWheelFront: IBikeWheelFront read FBikeWheelFront implements IBikeWheelFront;
       end;
    
    var
       Form1: TForm1;
    
    implementation
    
    {$R *.DFM}
    
    { TBikeWheel }
    
    procedure TBikeWheel.DoBikeWheel;
    begin
       ShowMessage('TBikeWheel.DoBikeWheel');
    end;
    
    { TBikeWheelFrontXYZ }
    
    constructor TBikeWheelFrontXYZ.Create;
    begin
       inherited Create;
       Self.FIBikeWheel := TBikeWheel.Create;
       Self.FBikeWheelFront := TBikeWheelFront.Create;
    end;
    
    { TBikeWheelFront }
    
    procedure TBikeWheelFront.DoBikeWheelFront;
    begin
       ShowMessage('TBikeWheelFront.DoBikeWheelFront');
    end;
    
    procedure TForm1.btnTestClick(Sender: TObject);
    var
       bikeWhell: TBikeWheelFrontXYZ;
    begin
       bikeWhell := nil;
       try
          try
             bikeWhell := TBikeWheelFrontXYZ.Create;
             IBikeWheelFront(bikeWhell).DoBikeWheelFront;
             IBikeWheel(bikeWhell).DoBikeWheel;
          except
             on E: Exception do
             begin
                raise;
             end;
          end;
       finally
          if Assigned(bikeWhell) then FreeAndNil(bikeWhell);
       end;                                          
    end;
    

提交回复
热议问题