每个用户的c#策略模式
作者:互联网
我有一个非常简单的场景.
我网站的用户可以是每月会员或每年会员
public class User
{
public string UserName { get; set; }
public MembershipType MembershipType { get; set; }
}
public enum MembershipType
{
MONTHLY,
ANNUALLY
}
然后根据成员资格,我采用不同的计费策略:
public interface IBillingStrategy
{
void Bill(User user);
}
if (user.MembershipType == MembershipType.ANNUALLY)
{
_billingStrategy = new AnnualBillingStrategy();
}
else if (user.MembershipType == MembershipType.MONTHLY)
{
_billingStrategy = new MonthlyBillingStrategy();
}
这非常简单明了.现在生意开始了,他说:“我想照顾我的朋友鲍勃,我希望你对他的帐单的计算方式与其他人略有不同!”
因此,如果我继续该模式,则可以制定BobBillingStrategy.然后我可以添加一些额外的逻辑,现在我有两种方法可以识别鲍勃
if (user.UserName.Equals("bob"))
{
_billingStrategy = new BobBillingStrategy();
}
因为我很难对用户名进行编码,所以这感觉很脏,只是我的运气鲍勃创建了一个新用户.因此,我可以向我的用户添加一个名为IsBob的布尔属性
if (user.IsBob)
{
_billingStrategy = new BobBillingStrategy();
}
两者似乎都让我觉得很有趣.我可以看到会发生什么,最终我将开始为Fred和Ted进行测试.我上面的代码可以工作,但是我确定必须有一个更干净的解决方案.
谢谢
解决方法:
我将拥有作为默认账单等的类的Membership,这将是一堆清洁工,如果有以下情况:
public class Membership
{
public String Name { get; private set; }
public BillingStrategy DefaultBillingStrategy {get; private set; }
//Other properties
public Membership(string name, BillingStrategy defaultBillingStrategy)
{
Name = name;
DefaultBillingStrategy = defaultBillingStrategy;
}
}
然后,您对用户执行以下操作:
public class User
{
//same as before
public BillingStrategy BillingStrategy {get; set; }
public User(string Name, Membership membership, BillingStrategy billingStrategy = null)
{
name = Name;
MemberShip = memberShip;
BillingStrategy = billingStrategy ? membership.DefaultBillingStrategy;
}
}
enter code here
也;由于用户不愿意在加入jul时支付jan thorugh jun的费用,因此您可能想保存有关该成员的成员资格到期时间的一些信息,并让成员资格在计费时/之后设置该值
标签:strategy-pattern,code-structure,c,design-patterns 来源: https://codeday.me/bug/20191029/1958269.html