频道直达 - 专题 - 新闻 - 技巧 - 组网 - 开发 - 安全 - web编程 - 图像 - 操作系统 - 数据库 - 教育 - 旅游 - 健康 - 时尚 - 驱动 - 软件 - 游戏 - 多媒体 - ERP - 讨论组

Java敏捷开发技巧之消除代码异味

来源:赛迪网 作者:yongbing 出处:巧巧读书 2007-12-28 进入讨论组
上一页 1 2 3 4 5 下一页 
谢 谢 收 藏 http://www.qqread.com/java/2007/12/w389616.html

条件下的代码还是不怎么一样,不如再抽象一点:

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

当然,我们需要在每种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就行了。

更多文章 更多内容请看Office技巧专区Java环境安装配置网管实用技巧100例专题,或进入讨论组讨论。
上一页 1 2 3 4 5 下一页 
收藏此文】【 】【打印】【关闭
相关图文阅读
频道图文推荐
健 康 咨 询
时 尚 咨 询
巧巧读书宗旨
相关专题
讨论组问题推荐
站内各频道最新更新文档
站内最新制作专题
热门关键字导读
Photoshop教 程照片处理 照片制作 PS快捷键 抠图
计 算 机 故 障XP系统修复
艺 术 与 设 计设计 流媒体 设计欣赏 边框
计 算 机 安 全ARP
站内频道文章精选
巧巧电脑频道编辑信箱  告诉我们您想看的专题或文章