多态(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;
}
}



最新文章

  1. Atitit利用反射获取子类 集合&#160;以及继承树
  2. Highcharts使用教程(2):设置选项
  3. Load Runner录制C/S客户端
  4. fuse入门
  5. 工作流模式与K2实现- (1)
  6. 【POJ 2886】Who Gets the Most Candies?
  7. Java初学(五)
  8. [转载] 单表60亿记录等大数据场景的MySQL优化和运维之道 | 高可用架构
  9. main函数参数的使用
  10. BW增强数据源的两种方法
  11. POJ 3692 Kindergarten (补图是二分图的最大团问题)
  12. vijos 1426
  13. 大数据学习系列之七 ----- Hadoop+Spark+Zookeeper+HBase+Hive集群搭建 图文详解
  14. OO第一次总结
  15. [转]linux查看日志文件内容命令
  16. Node.js创建本地简易服务器
  17. Oracle 口令文件:即 oracle密码文件
  18. 线上bug分析
  19. JavaScript复杂判断的更优雅写法
  20. mysql 8.0.12 创建新的数据库、用户并授权

热门文章

  1. css hack原理
  2. 每天复习Shell—ls
  3. JS之RegExp对象(二)
  4. ABAP 读取FTP文件
  5. mysql03---触发器
  6. UVA11324 The Largest Clique —— 强连通分量 + 缩点 + DP
  7. bzoj4806 炮——DP
  8. python名片管理系统V2
  9. 《Deep Learning Face Attributes in the Wild》论文笔记
  10. MVC视图中下拉框的使用