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

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

来源:赛迪网 作者:yongbing 出处:巧巧读书 2007-12-28 进入讨论组
上一页 1 2 3 4 5 下一页 

另一个例子

让我们来看一下另外一个例子。在当前的系统中,有三种用户:常规用户,管理员和游客。

常规用户必须每隔90天修改一次密码(更频繁也行)。管理员必须每30天修改一次密码。游客就不需要修改了。

常规用户跟管理员可以打印报表。

先看一下当前的代码:

class UserAccount {
final static int USERTYPE_NORMAL = 0;
final static int USERTYPE_ADMIN = 1;
final static int USERTYPE_GUEST = 2;
int userType;
String id; 
String name;
String password;
Date dateOfLastPasswdChange;
public boolean checkPassword(String password) {
...
}  

class InventoryApp {
void login(UserAccount userLoggingIn, String password) {
if (userLoggingIn.checkPassword(password)) {
GregorianCalendar today = new GregorianCalendar();
GregorianCalendar expiryDate = getAccountExpiryDate(userLoggingIn);
if (today.after(expiryDate)) {
//提示用户修改密码
...
}  
}  
}  
GregorianCalendar getAccountExpiryDate(UserAccount account) {
int passwordMaxAgeInDays = getPasswordMaxAgeInDays(account);
GregorianCalendar expiryDate = new GregorianCalendar();
expiryDate.setTime(account.dateOfLastPasswdChange);
expiryDate.add(Calendar.DAY_OF_MONTH, passwordMaxAgeInDays);
return expiryDate;
}  
int getPasswordMaxAgeInDays(UserAccount account) {
switch (account.getType()) {
case UserAccount.USERTYPE_NORMAL:
return 90;
case UserAccount.USERTYPE_ADMIN:
return 30;
case UserAccount.USERTYPE_GUEST:
return Integer.MAX_VALUE;
}  
}  
void printReport(UserAccount currentUser) {
boolean canPrint;
switch (currentUser.getType()) {
case UserAccount.USERTYPE_NORMAL:
canPrint = true;
break;
case UserAccount.USERTYPE_ADMIN:
canPrint = true;
break;
case UserAccount.USERTYPE_GUEST:
canPrint = false;
}
if (!canPrint) {
throw new SecurityException("You have no right");
}
//打印报表
}
}
 
用一个对象代替一种类别(注意,之前是一个类代替一种类别)。

根据之前讲的解决方法,要去掉类别代码,我们只需要为每种类别创建一个子类,比如:

abstract class UserAccount {
String id;  
String name;
String password;
Date dateOfLastPasswdChange;
abstract int getPasswordMaxAgeInDays(); 
abstract boolean canPrintReport();  
}  
class NormalUserAccount extends UserAccount {  
int getPasswordMaxAgeInDays() { 
return 90;  
}
boolean canPrintReport() {  
return true;
}
}  
class AdminUserAccount extends UserAccount {
int getPasswordMaxAgeInDays() { 
return 30;  
}
boolean canPrintReport() {  
return true;
}
}  
class GuestUserAccount extends UserAccount {
int getPasswordMaxAgeInDays() { 
return Integer.MAX_VALUE;
}
boolean canPrintReport() {  
return false;
}
}

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