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();
    }
  }
}

转载于:https://www.cnblogs.com/KarlZhang/p/9128103.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值