第一章 开闭原则

开闭原则(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);
		}
	}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值