一风子

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

参考自书籍:24种设计模式介绍与6大设计原则

策略模式的好处就是:体现了高内聚低耦合的特性

public class Strategy
{
    private Context context;
    public void Main()
    {
        Console.WriteLine("发生了第一个事件!需要想个办法!");
        context = new Context(new FristPlan());
        context.operate();

        Console.WriteLine("发生了第二个事件!需要想个办法!");
        context = new Context(new SecondPlan());
        context.operate();

        Console.WriteLine("发生了第三个事件!需要想个办法!");
        context = new Context(new ThirdPlan());
        context.operate();
    }
}

public class Context
{
    private IStrategy _strategy;

    public Context(IStrategy strategy)
    {
        _strategy = strategy;
    }

    public void operate()
    {
        _strategy.OPRT();
    }
}

public interface IStrategy
{
    void OPRT();
}

public class FristPlan : IStrategy
{
    public void OPRT()
    {
        Console.WriteLine("这是第一个计策!");
    }
}
public class SecondPlan : IStrategy
{
    public void OPRT()
    {
        Console.WriteLine("这是第二个计策!");
    }
}
public class ThirdPlan : IStrategy
{
    public void OPRT()
    {
        Console.WriteLine("这是第三个计策!");
    }
}

下面是执行代码:

class Program
{
        
    static void Main(string[] args)
    {
        Strategy strategy = new Strategy();
        strategy.Main();
    }
}

 

posted on 2020-06-01 18:59  一风子  阅读(19)  评论(0)    收藏  举报