Search code examples
realbasicrealstudio

REALbasic: Sharing common code between disparate subclasses


I have two separate classes (A = a subclass of BevelButtom, B = a subclass of PushButton). Both A and B implement a number of identical methods in exactly the same way. Since both subclasses' superclasses are different and since RB doesn't support multiple inheritance, all I can do to tie these methods together is define a class interface, have both subclasses implement the interface, then copy/paste the method bodies in each subclass.

That offends my sensibilities. Is there a way in RB to extract this common logic elsewhere?

Thanks!


Solution

  • Using an interface seems like the right approach, but rather than copying the method bodies to each subclass, I think it makes more sense to create a new class (say CommonButtonStuff) with the common code. Then you can call it in the implemented methods:

    CommonButtonInterface
      Sub Method1
    
    Class CommonButtonHandler
      Sub DoMethod1
        MsgBox("Do it!")
      End Sub
    
    Class A Inherits From PushButton, Implements CommonButtonInterface
      Private Property mCommonStuff As CommonButtonHandler
    
      Sub Constructor
        mCommonStuff = New CommonButtonHandler
      End Sub
    
      Sub Method1
        mCommonStuff.DoMethod1
      End Sub
    
    Class B Inherits From BevelButton, Implements CommonButtonInterface
      Private Property mCommonStuff As CommonButtonHandler
    
      Sub Constructor
        mCommonStuff = New CommonButtonHandler
      End Sub
    
      Sub Method1
        mCommonStuff.DoMethod1
      End Sub