How to implement identical methods with 2 and more Classes?

后端 未结 2 1628
一生所求
一生所求 2021-01-18 11:58

I want to write a TCheckBox and TRadioButton descendants having 3 identical methods.

TMyCheckBox = class(TCheckBox)
  procedure DoS         


        
2条回答
  •  孤街浪徒
    2021-01-18 12:50

    Define an interface say IDoSomething with the the three method signatures.

    Then change your class declaration to

    TMyCheckBox = class(TCheckBox, IDoSomething)
    

    and then implement.

    If the implementations are common or very close.

    Then define a helper class TDoSomething and then delegate the work.

    e.g.

    Procedure TMyCheckBox.DoSomething1; // implements IDoSomething1
    Begin
      TDoSomething.DoSomething1(Self); // given class method will suffice.
    End;
    

    Class Methods in delphi, equivalent to static methods in other languages.

    Type
        TDoSomethingHelper = Class(TObject)
        Public
          Class Procedure DoSomething1(aComponent : TComponent);
        End;
    
    ...
    implementation
    
    Class Procedure TDoSomethingHelper.DoSomething1(aComponent : TComponent);
    Begin
      aComponent.Tag = 27;
    End;
    

提交回复
热议问题