或者switch)
经常地,为了去掉if-then-else-if或者switch,我们需要先保证在每个条件分支下的要写的代码是一样的。在drawShapes这个方法里面,我们先以一个较抽象的方法(伪码)来写吧!
class CADApp {
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
if (shapes[i] instanceof Line) {
画线条;
} else if (shapes[i] instanceof Rectangle) {
画长方形;
} else if (shapes[i] instanceof Circle) {
画圆;
}
}
}
}
条件下的代码还是不怎么一样,不如再抽象一点:
class CADApp {
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
if (shapes[i] instanceof Line) {
画出形状;
} else if (shapes[i] instanceof Rectangle) {
画出形状;
} else if (shapes[i] instanceof Circle) {
画出形状;
}
}
}
}
好,现在三个分支下的代码都一样了。我们也就不需要条件分支了:
class CADApp {
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
画出形状;
}
}
}
最后,将“画出形状”这个伪码写成代码吧!
class CADApp {
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
shapes[i].draw(graphics);
}
}
}
Java敏捷开发技巧之消除代码异味(5)
时间:2011-04-09
当然,我们需要在每种Shape的类里面提供draw这个方法:
abstract class Shape {
abstract void draw(Graphics graphics);
}
class Line extends Shape {
Point startPoint;
Point endPoint;
void draw(Graphics graphics) {
graphics.drawLine(getStartPoint(), getEndPoint());
}
}
class Rectangle extends Shape {
Point lowerLeftCorner;
Point upperRightCorner;
void draw(Graphics graphics) {
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
}
}
class Circle extends Shape {
Point center;
int radius;
void draw(Graphics graphics) {
graphics.drawCircle(getCenter(), getRadius());
}
}
将抽象类变成接口
现在,看一下Shape这个类,它本身没有实际的方法。所以,它更应该是一个接口:
interface Shape {
void draw(Graphics graphics);
}
class Line implements Shape {
...
}
class Rectangle implements Shape {
...
}
class Circle implements Shape {
...
}
改进后的代码
改进后的代码就像下面这样:
interface Shape {
void draw(Graphics graphics);
}
class Line implements Shape {
Point startPoint;
Point endPoint;
void draw(Graphics graphics) {
graphics.drawLine(getStartPoint(), getEndPoint());
}
}
class Rectangle implements Shape {
Point lowerLeftCorner;
Point upperRightCorner;
void draw(Graphics graphics) {
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
}
}
class Circle implements Shape {
Point center;
int radius;
void draw(Graphics graphics) {
graphics.drawCircle(getCenter(), getRadius());
}
}
class CADApp {
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
shapes[i].draw(graphics);
}
}
}
如果我们想要支持更多的图形(比如:三角形),上面没有一个类需要修改。我们只需要创建一个新的类Triangle就行了。
Java敏捷开发技巧之消除代码异味(6)
时间:2011-04-09
另一个例 |