Enumeration strategy

Enumeration strategy is to write tricky code, an abstract method for the enumeration of the corresponding enumeration type is the need to implement the abstract methods, so there would be drawbacks, and some possible methods of content need to implement an enumerated type is the same, it seems very clear that this code will be repeated for this problem can use policies enumeration, enumeration of this strategy in the idea is to reuse code, the focus is how to achieve the look clever code reuse code below

* Class Description: calculating overtime, working overtime 2 times, holidays 3 times
* /

public enum BetterPayDay {
MONDAY(PayType.WORK), TUESDAY(PayType.WORK), WEDNESDAY(
PayType.WORK), THURSDAY(PayType.WORK), FRIDAY(PayType.WORK), 
SATURDAY(PayType.REST), SUNDAY(PayType.REST),WUYI(PayType.REST);

private final PayType payType;//成员变量

BetterPayDay(PayType payType) {
this.payType = payType;
}

double pay(double hoursOvertime) {
return payType.pay(hoursOvertime);
}

//策略枚举 
private enum PayType {
WORK {
double pay(double hoursOvertime) {
return hoursOvertime*HOURS_WORK;
}
},
REST {
double pay(double hoursOvertime) {
return hoursOvertime*HOURS_REST;
}
};

private static final int HOURS_WORK = 2;
private static final int HOURS_REST = 3;

abstract double pay(double hoursOvertime);//抽象计算加班费的方法
}

public static void main(String[] args) {
System.out.println(BetterPayDay.MONDAY.pay(7.5));
}
}

 


 Method of calculating overtime if that is not the way to write the enumeration settlement policy, but in an abstract way to write BetterPayDay, then Monday to Friday are the same code multiplied by 2 times the wages, so that duplication of code, apparently to write inappropriate, this is an internal class in the definition of an enumeration, enumeration behavior of this class is specifically defined in the calculation of overtime pay, so enumeration define two types of behavior a weekday overtime is calculated, and the other is calculated holiday overtime, then the corresponding incoming BetterPayDay enumerated type enumeration class each enumeration type parameter, i.e. in the instance of a policy configuration BetterPayDay enumeration class should pass, this member should be so variable BetterPayDay private final payType payType; such a method can be used, variables calculated overtime unified call. Achieve the purpose of code reuse, the program is more elegant!

Summary: Enumeration between instances have the same behavior, the common code of conduct drawn to enumerate instances, namely two enumerations to define the behavior! ! !

Guess you like

Origin www.cnblogs.com/wcss/p/12124065.html