开闭原则(Open Closed Principle,OCP):指的是一个软件实体应对对扩展开发,对修改关闭(Software entities should be open for extension, but closed for modification)。
举出一个反例:
public Money caculaterPay(Employee e) throws InvalidEmployeeType {
int type = e.getType();
switch (type) {
case COMMISSIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateHourlyPay(e);
case SALARIED:
return calculateSalaryedPay(e);
default:
throw new InvalidEmployeeType(type);
}
}
这段代码就违反一开闭原则:因为每次添加新员工,都要对其进行修改,不符合对修关闭的原则
在计算这一块要符合开闭,该修改如下:
public abstract class Employee {
public abstract Money caculaterPay();
}
public static void main(String[] args) {
Employee e = new Employee() {
//根据多态来进行领取
@Override
public Money caculaterPay() {
return new Money(100,"RMB");
}
};
System.out.println(e.caculaterPay());
}
不过就算这样在判定员工类型方面,也只能提供最大复用性的工厂模式:
public class EmployeeRecord {
public int type;
}
public interface EmployeeFactory {
Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType;
}
public class EmployeeFactoryimpl implements EmployeeFactory {
private final int COMMISSIONED =1;
private final int HOURLY = 2;
private final int SALARIED = 3;
@Override
public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType {
switch (r.type) {
case COMMISSIONED:
return new CommissionedEmployee(r);
case HOURLY:
return new HourlyEmployee(r);
case SALARIED:
return new SalariedEmployee(r);
default:
throw new InvalidEmployeeType(r.type);
}
}
}