C#机房重构-下机(策略模式)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/TheBestAge/article/details/82260646
策略模式

策略模式UML图
策略模式:定义算法家族,分别封装,让它们之间可以相互替换,此模式计算法的变化,不会影响到使用算法的客户。策略模式封装了变化,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式

具体实现

Context类

  public class Context
{
    private Strategy strategy;
    public Context(Strategy strategy)
    {
        this.strategy = strategy;
    }
    public Line_info ContextInterface(Entity.Line_info line)
    {
        strategy.Getconsum(line);
        return line;
    }
}

抽象类,定义抽象方法

public abstract class Strategy//策略抽象类
{
    //定义一个获得消费金额的抽象方法
    public abstract Line_info Getconsum(Entity.Line_info line);
}

具体算法或行为1

public class Strategyone : Strategy//具体策略类1
{
    public override Line_info Getconsum(Entity.Line_info line)//临时用户消费金额
    {
        //获取临时用户单位消费金额
        line.Consume = line.ConsumeTime * line.tmpRate;
        return line;
    }
}

具体算法或行为2

 public class Strategytwo : Strategy//具体策略类2
{
    public override Line_info Getconsum(Line_info line)//固定用户消费金额
    {
        //获取固定用户单位消费金额
        line.Consume = line.ConsumeTime * line.Rate;
        return line;
    }
}

BLL层

 string type = line.Type;
        switch (type)
        {
            case "固定用户":                   
                Context context = new Context(new Strategyone());
                line=context.ContextInterface(line);
                break;

            case "临时用户":                  
                Context context1 = new Context(new Strategytwo());
                line=context1.ContextInterface(line);
                break;              
        }

总结

选择所有具体实现的职责是由客户端对象承担的,并转给策略模式的Context对象。可以通过策略模式和简单工厂结合,将选择具体实现的职责由Context来承担。

猜你喜欢

转载自blog.csdn.net/TheBestAge/article/details/82260646