软件设计重构秘笈31式-30使用多态代替条件判断
概念
本文中的”使用多态代替条件判断”是指如果你需要检查对象的类型或者根据类型执行一些操作时,一种很好的办法就是将算法封装到类中,并利用多态性进行抽象调用。
意图
本文展示了面向对象编程的基础之一“多态性”, 有时你需要检查对象的类型或者根据类型执行一些操作时,一种很好的办法就是将算法封装到类中,并利用多态性进行抽象调用。
如下代码所示,OrderProcessor 类的ProcessOrder方法根据Customer 的类型分别执行一些操作,正如上面所讲的那样, 我们最好将OrderProcessor 类中这些算法(数据或操作)封装在特定的Customer 子类中。
案例
public class OrderProcessor {
public double processOrder(Customer customer, List<Product> products)
{
// do some processing of order
double orderTotal = products.stream().mapToDouble(Product::getPrice).sum();
String customerType = customer.getType();
if (customerType.equals("employee"))
{
orderTotal -= orderTotal * 0.15;
}
else if (customerType.equals("nonemployee"))
{
orderTotal -= orderTotal * 0.05;
}
return orderTotal;
}
}
public abstract class Customer {
protected abstract String getType();
}
public class Employee extends Customer {
@Override
protected String getType() {
return "employee";
}
}
public class NonEmployee extends Customer {
@Override
protected String getType() {
return "nonemployee";
}
}
public class Product {
private double price;
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
重构
重构后的代码如下,每个Customer 子类都封装自己的算法,然后OrderProcessor 类的ProcessOrder方法的逻辑也变得简单并且清晰了。
public class OrderProcessor {
public double processOrder(Customer customer, List<Product> products)
{
// do some processing of order
double orderTotal = products.stream().mapToDouble(Product::getPrice).sum();
orderTotal -= orderTotal * customer.discountPercentage();
return orderTotal;
}
}
public abstract class Customer {
protected abstract String getType();
public abstract double discountPercentage();
}
public class Employee extends Customer {
@Override
protected String getType() {
return "employee";
}
@Override
public double discountPercentage() {
return 0.15;
}
}
public class NonEmployee extends Customer {
@Override
protected String getType() {
return "nonemployee";
}
@Override
public double discountPercentage() {
return 0.05;
}
}
public class Product {
private double price;
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
总结
”使用多态代替条件判断“这个重构在很多时候会出现设计模式中(常见的工厂家族、策略模式等都可以看到它的影子), 因为运用它可以省去很多的条件判断,同时也能简化代码、规范类和对象之间的职责。