代码重构- - -多态+工厂模式替换Switch

代码重构- - -多态+工厂模式替换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;
        }
    }
}

<二> 利用多态

  1. 创建一个接口Discount;
public interface Discount{
    public double getDiscount();
}
  1. 每种不同类型的人都创建一个类并继承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;

    }
}
  1. 修改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:

  1. 同<二>2
  2. 创建折扣工厂
public class DiscountFactory {
       public Object getDiscountInstance(Class<?> cls) throws Exception{
             Object obj = cls.newInstance();
             return obj;
       }
}
  1. 计算某类型顾客的折扣(以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结构不利于代码的维护和扩展,比如,以后有新的分支加入,就需要修改原来的类,违反了开闭原则;但是结构清晰,容易理解;而利用多态+工厂模式却能很轻易的扩展代码,缺点是:设计起来比较复杂,代码阅读起来需要不停切换上下文,不易于理解和快速开发,此外,这种方式会产生很多的子类,也不太利于代码的阅读;

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值