下载安卓APP箭头
箭头给我发消息

客服QQ:3315713922

Java开发技巧之消除代码异味(5)

作者:课课家教育     来源: http://www.kokojia.com点击数:702发布时间: 2016-02-03 13:52:14

标签: java编程java开发java入门

大神带你学编程,欢迎选课

  当然,我们需要在每种Shape的类里面提供draw这个方法:

  abstract class Shape {

  abstract void draw(Graphics graphics);

  }

Java开发技巧之消除代码异味(5)_java编程网站_java手游开发_课课家

  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就行了。

赞(0)
踩(0)
分享到:
华为认证网络工程师 HCIE直播课视频教程