使用策略模式重构代码 [英] Refactoring code using Strategy Pattern
问题描述
我们如何使用Strategy模式重构GiftCouponPayment类,以便在GetCouponValue方法的策略时不需要更改类?
更新:在分析职责后,我觉得GiftCoupon将成为GiftCouponPayment课程的更好名称。
C#代码
public int GetCouponValue()
{
int effectiveValue = -1;
if(CouponNumber< 2000)
{
effectiveValue = 0;
}
else
{
effectiveValue = CouponValue;
}
return effectiveValue;
}
阅读
您可以将优惠券价值政策注入优惠券对象本身并呼吁它计算优惠券价值。在这种情况下,可以通过这个
到策略中,以便策略可以向优惠券询问其所需的属性(例如优惠券编号):
public interface ICouponValuePolicy
{
int ComputeCouponValue(GiftCouponPayment couponPayment);
}
public class GiftCouponPayment
{
public ICouponValuePolicy CouponValuePolicy {
get;
设置;
}
public int GetCouponValue()
{
return CouponValuePolicy.ComputeCouponValue(this);
}
}
此外,它似乎是您的 GiftCouponPayment
真的负责两件事(付款和礼品券)。提取 GiftCoupon
类包含 CouponNumber
, CouponValue $ c可能是有意义的$ c>和
GetCouponValue()
,并从 GiftCouponPayment
中引用。
I have a GiftCouponPayment class. It has a business strategy logic which can change frequently - GetCouponValue(). At present the logic is "The coupon value should be considered as zero when the Coupon Number is less than 2000". In a future business strategy it may change as "The coupon value should be considered as zero when the Coupon Issued Date is less than 1/1/2000". It can change to any such strategies based on the managing department of the company.
How can we refactor the GiftCouponPayment class using Strategy pattern so that the class need not be changed when the strategy for GetCouponValue method?
UPDATE: After analyzing the responsibilities, I feel, "GiftCoupon" will be a better name for "GiftCouponPayment" class.
C# CODE
public int GetCouponValue()
{
int effectiveValue = -1;
if (CouponNumber < 2000)
{
effectiveValue = 0;
}
else
{
effectiveValue = CouponValue;
}
return effectiveValue;
}
READING
You can inject a "coupon value policy" into the coupon object itself and call upon it to compute the coupon value. In such cases, it is acceptable to pass this
into the policy so that the policy can ask the coupon for its required attributes (such as coupon number):
public interface ICouponValuePolicy
{
int ComputeCouponValue(GiftCouponPayment couponPayment);
}
public class GiftCouponPayment
{
public ICouponValuePolicy CouponValuePolicy {
get;
set;
}
public int GetCouponValue()
{
return CouponValuePolicy.ComputeCouponValue(this);
}
}
Also, it seems like your GiftCouponPayment
is really responsible for two things (the payment and the gift coupon). It might make sense to extract a GiftCoupon
class that contains CouponNumber
, CouponValue
and GetCouponValue()
, and refer to this from the GiftCouponPayment
.
这篇关于使用策略模式重构代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!