上一节的代码中含有大量的重复内容,这会影响程序的执行效率。进行编程时,出现这样的重复内容就表明它是一个不好的架构,需要维护成倍的代码而且大大增加了出错的可能性。我们需要将上一节的Circle类,Rectangle类以及OlateSpheroid类统一起来,这就要用到继承的知识,借图:
使用继承改进Shape类架构
我们先定义Shape的基类ShapeBase,如下所示:
// the interface of Base Shape
@interface ShapeBase: NSObject
{
ShapeColor fillColor;
ShapeRect bounds;
}
- (void) setFillColor: (ShapeColor) color;
- (void) setBounds: (ShapeRect) bs;
- (void) draw;
@end
@implementation ShapeBase
- (void) setFillColor:(ShapeColor)color
{
fillColor = color;
} // setFillColor
- (void) setBounds:(ShapeRect)bs
{
bounds = bs;
} // setBounds
- (void) draw
{
}
@end // shapebase
然后Circle类,Rectangle类等分别继承自ShapeBase类,写一下Circle类,如下:
// the interface of Class Circle
@interface Circle: ShapeBase
@end // circle
@implementation Circle
- (void) draw
{
NSLog(@"draw a circle at ( %d %d %d %d ) in %@", bounds.x, bounds.y, bounds.width, bounds.height, colorName(fillColor));
} // draw
@end // Circle implementation
其中,interface不需要写什么,只需要在implementation中再实现一下draw方法即可。Rectangle类以及OlateSpheroid类修改与Circle类相同。
运行程序可以看出,它的功能和上一节完全相同。但我们并没有更改main()函数中设置和适用对象的任何代码。这是因为我们没有改变对象的响应方法,同时也没有修改它的行为。
这种移动和简化代码的方式成为重构。进行重构时,通过移动某些代码来改进程序的架构,正如我们在这里删除重复的代码,而不改变代码的行为或运行结果一样。通常的开发周期包括向代码中添加某些特性,然后通过重构删除所有重复的代码。通常,在面向对象的程序中添加某些新特性后,程序反而变得更简单,就像我们添加了ShapeBase类后所出现的情况。
改变方法的实现时,需要重写(override)继承方法。Circle具有自己的draw方法,因此,可以说它重写了draw方法。代码运行时,Objective-C确保调用相应类的重写方法的实现。

使用继承改进Shape类架构











网友评论