views:

61

answers:

3

I'm creating a custom Layout for android. The layout implementation is exactly the same, but once I need to extend from RelativeLayout, and once from LinearLayout.

class Layout1 extends LinearLayout {
// methods and fields
}

class Layout2 extends RelativeLayout {
// the same EXACT methods and fields
}

How can I use inheritance to avoid code duplication and implement my methods once.

A: 

I do not know if it will fit your use case, but you might consider using delegation by adding a field of the "other" class.

I am pessimistic though as tha classes are too closely related.

Peter Tillemans
+2  A: 

You could use composition and something like the "strategy" pattern:

class YourLayout extends ViewGroup {
    ViewGroup strategy;
    public YourLayout( Condition someCondition ) {
       if( someCondition.useLinear() ) {
            strategy = new LinearLayout(); // or Layout1
       } else {
            strategy = new RelativeLayout();
       }
    }
    public View findFocus() {
        return strategy.findFocus();
    }
    .... rest of the methods:
    / rest of specific EXACT methods and fields
 }

You may even change the strategy at runtime.

This way your YourLayout class may use both scenarios.

OscarRyz
And if this is too complicated for your purposes, i would suggest implementing an abstract ViewGroup that contains all of the common behaviors, and then have your two layouts extend the abstract ViewGroup with their specific behavior.
mtmurdock
that is not possible if he already wants to extend linear or relativelayout...
Janusz
A: 

I used delegation, although somewhat differently. The only overloaded method I have in my class was an overloaded dispatchDraw. So I moved it to a different class and included an instance of it in each of the classes that extend.

 class MyLinearLayout extends LinearLayout {
        MyDraw md = new MyDraw();

        @Override
        protected void dispatchDraw(Canvas canvas) {    
            md.draw(canvas);
            super.dispatchDraw(canvas);
        }
 }

 class MyRelativeLayout extends RelativeLayout {
      //    as above
 }

Although I still have two classes that extend, but I'm not duplicating the code that was duplicated before which was what I wanted to achieve.

Itsik