Software Construction Series(3)
在Code时经常会遇到大量使用if-else或者case的情况,往往会把Code的Smell变坏。其中一种情况具有这样的结构:
class shape {
String type;
String getType();
...
}
class Circle extends Shape {
Circle() {
super.type = "Circle";
}
String getType() {
return type;
}
}
class Rectangle extends Shape {
...
}
...
class ShapeFactory {
public void drawShape(Shape s) {
switch (s.getType()) {
case "Circle": {
...
}
case "Rectangle": {
}
...
default: {
...
}
}
}
}
has a bad smell 的原因是这段代码不便于扩展,当要添加新的Shape时,需要同时在ShapeFactory中添加新的类。换句话说,这段代码相互依赖的程度比较高(耦合度(coupling)高),导致不利于扩展。一个比较好的做法是:
abstract class shape {
String type;
String getType();
abstract void draw();
...
}
class Circle extends Shape {
Circle() {
super.type = "Circle";
}
String getType() {
return type;
}
@Override
void draw() {
...
}
}
class Rectangle extends Shape {
...
}
...
class ShapeFactory {
public void drawShape(Shape s) {
s.draw();
}
}
}
原理:把draw的task委派给其他的类来做,每个具体实现该method的类分别实现各自的task,从而避免了在一个类中根据case来统一完成task的工作(把task分布下去)。如果在原来的类中(即Shape)不适合进行这样的扩展。不妨使用Decorator模式,即
interface drawable {
void draw() {
...
}
}
abstract class drawableShape implements drawable {
Shape s;
public drawableShape(Shape a) {
s = a;
}
public abstract void draw();
}
class drawableCircle extends drawableShape {
public drawableCircle(Shape a) {
super(a);
}
@Override
public void draw() {
...
}
}
class ShapeFactory {
public void drawShape(drawable s) {
s.draw();
}
}
}