1.方法抽取:Extract Method
将calcCost中参数校验部分抽取成方法verify.
选定代码--->右键Refactor-->Extract Method
2.重命名:Rename
(1)重命名类名Test1为CostCalculator
(2)重命名User为UserInfo
选定类名-->右键Refactor-->Rename
3.内联:Inlining
内联方法add
内联原因:调用方法越多,运行速度越慢
选定方法名("add")-->右键Refactor-->Inline
4.常量抽取:Extract Constant
原因:避免手误
将"normal","vip"抽取成常量
选定字符串-->右键Refactor-->Extract Constant
5.抽取局部变量:Extract Local Voriable
将user,userType抽取成变量
原因:减少代码长度,增加代码可读性
选定要抽取的变量(user.userName)-->右键Refactor-->Extract Local Variable
6.包装字段:Encapsulate Field
重构user类,用set,get包装
主菜单-->Refactor-->Encapsulate Field
7.抽取接口:Extract Interface
选定方法名(calcCost)-->右键Refactor-->Extract Interface-->Name:ICcstCalculator
重构后的代码为:
(一)UserInfo.java
package com.comnew.demo;
public class UserInfo {
private String userName;
private String userType;
private int amount;
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getUserType() {
return userType;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
}
(二)CostCalculator.java
package com.comnew.demo;
public class CostCalculator implements ICostCalculator {
private static final int VIPPRICE = 0;
private static final int NORMALPRICE = 10;
private static final String VIP = "vip";
private static final String NORMAL = "normal";
/* (non-Javadoc)
* @see com.comnew.demo.ICostCalculator#calcCost(com.comnew.demo.UserInfo)
*/
public int calcCost(UserInfo user)
{
verify(user);
int ret=0;
String userType = user.getUserType();
if(userType.equals(NORMAL))
{
ret=user.getAmount()+NORMALPRICE;
}
else if(userType.equals(VIP))
{
ret=user.getAmount()+VIPPRICE;
}
else
{
throw new IllegalArgumentException("useType的类型错误!必须未如下几种:"+NORMAL+","+VIP);
}
return ret;
}
private void verify(UserInfo user) {
String useType = user.getUserType();
if(useType==null)
{
throw new IllegalArgumentException("userType不能为空!");
}
if(user.getAmount()<=0)
{
throw new IllegalArgumentException("amount必须大于0!");
}
}
public static void main(String[] args)
{
String userName="tom";
String userType=NORMAL;
int amount=20;
UserInfo user=new UserInfo();
user.setUserName(userName);
user.setUserType(userType);
user.setAmount(amount);
System.out.println(new CostCalculator().calcCost(user));
}
}
(三)ICostCalculator.java
package com.comnew.demo;
public interface ICostCalculator {
public abstract int calcCost(UserInfo user);
}