zoukankan      html  css  js  c++  java
  • 重构31-Replace conditional with Polymorphism(多态代替条件)

    多态(Polymorphism)是面向对象编程的基本概念之一。在这里,是指在进行类型检查和执行某些类型操作时,最好将算法封装在类中,并且使用多态来对代码中的调用进行抽象。
    public class OrderProcessor {
    public Double ProcessOrder(Customer customer, List<Product> products) {
    // do some processing of order
    Double orderTotal = sum(products);
    Type customerType = customer.GetType();
    if (customerType == typeof(Employee)) {
    orderTotal -= orderTotal * 0.15d;
    } else if (customerType == typeof(NonEmployee)) {
    orderTotal -= orderTotal * 0.05d;
    }
    return orderTotal;
    }
    }
    如你所见,我们没有利用已有的继承层次进行计算,而是使用了违反SRP原则的执行方式。要进行重构,我们只需将百分率的计算置于实际的customer类型之中。我知道这只是一项补救措施,但我还是会这么做,就像在代码中那样
    public abstract class Customer {
    }

    public class Employee extends Customer {
    }

    public class NonEmployee extends Customer {
    }

    public abstract class Customer {
    public abstract Double DiscountPercentage(){
    return null;
    }
    }
    public class Employee extends Customer {
    @Override
    public Double DiscountPercentage(){
    return 0.15d;
    }
    }
    public class NonEmployee extends Customer {
    @Override
    public Double DiscountPercentage(){
    return 0.05d;
    }
    }
    public class OrderProcessor {
    public Double ProcessOrder(Customer customer, List<Product> products) { // do some processing of order
    Double orderTotal = sum(products);
    orderTotal -= orderTotal * customer.DiscountPercentage();
    return orderTotal;
    }
    }







  • 相关阅读:
    Python:Fatal error in launcher: Unable to create process using 问题排查
    接口测试及接口Jmeter工具介绍
    bug的分类和等级
    如何编写测试用例
    网络流入门--最大流算法Dicnic 算法
    Codevs 1004 四子连棋
    洛谷 P1072 Hankson 的趣味题
    Codevs 搜索刷题 集合篇
    洛谷 P1195 口袋的天空
    洛谷 P1362 兔子数
  • 原文地址:https://www.cnblogs.com/jgig11/p/5786509.html
Copyright © 2011-2022 走看看