代码重构- - -多态+工厂模式替换Switch
一、问题描述:
有一个演出类:Show,演出类里面能有一个获取折扣方法getDiscount(int type),根据不同类型的顾客提供不同的计算折扣方式;
二、Code
<一>Switch结构:
public class Show{
public static final int SVIP = 1;
public static final int VIP = 2;
public static final int NORMAL = 3;
......... // 其他部分
public double getDiscount(int type){
Switch(type){
case 1: 计算方式1; return discount1; break;
case 2: 计算方式2; return discount2;break;
case 3: 计算方式3; return discount3;break;
}
}
}
<二> 利用多态
- 创建一个接口Discount;
public interface Discount{
public double getDiscount();
}
- 每种不同类型的人都创建一个类并继承Discount接口,将计算方法写在重写后的方法里;
public class SvipDiscount implements Discount{ public double getDiscount(){
计算方式1,得到discount1;
return discount1;
}
}
public class VipDiscount implements Discount{
public double getDiscount(){
计算方式2,得到discount2;
return discount2;
}
}
public class NormalDiscount implements Discount{
public double getDiscount(){
计算方式3,得到discount3;
return discount3;
}
}
- 修改Show类:
public class discountFactory{
Discount discount;
public static final int SVIP = 1;
public static final int VIP = 2;
public static final int NORMAL = 3;
......... // 其他部分
public double getDiscount(int type){
Switch(type){
case 1: discount = new SvipDiscount();
case 2: discount = new VipDiscount();
case 3: discount = new NormalDiscount();
}
return discount.getDiscount();
}
}
<三>使用反射机制实现工厂模式替换switch:
- 同<二>2
- 创建折扣工厂
public class DiscountFactory {
public Object getDiscountInstance(Class<?> cls) throws Exception{
Object obj = cls.newInstance();
return obj;
}
}
- 计算某类型顾客的折扣(以VIP为例):
public class Test{
public static void main(String[] args){
DiscountFactory factory = new DiscountFactory();
Discount discount = null;
try {
discount = (VIPDiscount)factory.getDiscountInstance(VIPDiscount.class);
double result = discount.getDiscount();
System.out.println(result);
} catch (Exception e) {
System.out.println();
}
}
}
三、总结
Switch结构不利于代码的维护和扩展,比如,以后有新的分支加入,就需要修改原来的类,违反了开闭原则;但是结构清晰,容易理解;而利用多态+工厂模式却能很轻易的扩展代码,缺点是:设计起来比较复杂,代码阅读起来需要不停切换上下文,不易于理解和快速开发,此外,这种方式会产生很多的子类,也不太利于代码的阅读;