Inheritance question / problem
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 LinearLay开发者_运维问答out.
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.
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.
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.
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.
精彩评论