1

I have the following structure... Three controls made by me, that inherit from the same common control TCustomControl.

TDriveBar [MyShell.pas] > TCustomPanel [Vcl.ExtCtrls.pas] > TCustomControl [Vcl.Controls.pas]...

TPathBar [MyShell.pas] > TCustomControl [Vcl.Controls.pas]...

TFileList [MyShell.pas] > TCustomSuperList [MySuperList.pas] > TCustomControl [Vcl.Controls.pas]...

Now, I would like to change something so that my TDriveBar, TPathBar and TFileList can be accessed (typecast) as a common ancestor class and have some new methods in common. That ancestor seems to be TCustomControl, but I don't know if it's possible to insert a new class there. Even more, I would prefer that TCustomSuperList not to contain those new methods when it's used alone. I don't know if I made myself understood...

I cannot use interfaces because the idea is to write the common methods only once and use them in those thre controls... With an interface, I have to implement it in every Shell control...

fpiette
  • 11,983
  • 1
  • 24
  • 46
Marus Gradinaru
  • 2,824
  • 1
  • 26
  • 55
  • I don't see how what you're asking would work, because neither `TDriveBar` or `TFileList` descends directly from `TCustomControl`; `TDriveBar` descends from `TCustomPanel`, and `TFileList` descends from `TCustomSuperList`. You can't inject a new class between `TCustomControl` and `TCustomPanel`, and the same thing applies to `TFileList`. – Ken White Jan 29 '21 at 00:20
  • 1
    Single inheritance says no – David Heffernan Jan 29 '21 at 00:58
  • 2
    Without interfaces, this is simply not possible. However, there is nothing preventing you from writing a standalone set of functions or a helper class to implement the common functionality, and then you can have each component implement the common interface and internally delegate its implementation to the common functions/class. – Remy Lebeau Jan 29 '21 at 01:28
  • @RemyLebeau But if I do that, I cannot acces the properties of my control from the interface methods, isn't it ? I think that I must implement the interface in all three controls... – Marus Gradinaru Jan 29 '21 at 11:34
  • @MarusNebunu yes, you can. Simply pass in the control's `Self` pointer as a parameter to the object/functions that implement the interface methods. Yes, you have to implement the interface in all three controls, but you can delegate that implementation elsewhere – Remy Lebeau Jan 29 '21 at 15:13

1 Answers1

2

Delphi has the ability to delegate the methods of an interface to another object using the keyword implements.

In your case, the idea is to create an object implementing an interface with the common methods and in each of your components you create a property having the interface type and delegated to the object.

fpiette
  • 11,983
  • 1
  • 24
  • 46