一个可行的方案是,创建一个RectangularComponent类,里面有width,height,setWidth和setHeight这四样。然后让Button继承自这个类:
abstract class Component {
boolean isVisible;
int posXInContainer;
int posYInContainer;
...
abstract void paint(Graphics graphics);
}
abstract class RectangularComponent extends Component {int width;int height;
void setWidth(int newWidth) {
...
}
void setHeight(int newHeight)
{
...
}
}
class Button extends RectangularComponent {
ActionListener listeners[];
...
void paint(Graphics graphics) {
...
}
}
class ClockComponent extends Component {
...
void paint(Graphics graphics)
{
//根据时间绘制当前的钟表图形
}
}
这并不是唯一可行的方法。另一个可行的方法是,创建一个RectangularDimension,这个类持有这四个功能,然后让Button去代理这个类:
abstract class Component {
boolean isVisible;
int posXInContainer;
int posYInContainer;
...
abstract void paint(Graphics graphics);
}
class RectangularDimension {
int width; int height;
void setWidth(int newWidth)
{
...
}
void setHeight(int newHeight)
{
...
}
}
class Button extends Component {
ActionListener listeners[];
RectangularDimension dim;
...
void paint(Graphics graphics) {
...
}
void setWidth(int newWidth) {
dim.setWidth(newWidth);
}
void setHeight(int newHeight) {
dim.setHeight(newHeight);
}
}
class ClockComponent extends Component {
...
void paint(Graphics graphics)
{
//根据时间绘制当前的钟表图形
}
}
总结
当我们想要让一个类继承自另一个类时,我们一定要再三的检查:子类会不会继承了一些它不需要的功能(属性或者方法)?如果是的话,我们就得认真再想想:它们之间有没有真正的继承关系?如果没有的话,就用代理。如果有的话,将这些不用的功能从基类转移到另外一个合适的地方去。
引述
里斯科夫替换原则(LSP)表述:Subtype must be substitutable for their base types. 子类应该能够代替父类的功能。或者直接点说,我们应该做到,将所有使用父类的地方改成使用子类后,对结果一点影响都没有。或者更直白一点吧,请尽量不要用重载,重载是个很坏很坏的主意!