52

我一直在阅读策略模式,并且有一个问题。我在下面实现了一个非常基本的控制台应用程序来解释我在问什么。

我已经读过,在实施策略模式时,使用“switch”语句是一个危险信号。但是,我似乎无法摆脱在这个例子中使用 switch 语句。我错过了什么吗?我能够从Pencil中删除逻辑,但我的Main现在有一个 switch 语句。我知道我可以轻松创建一个新的TriangleDrawer类,而不必打开Pencil类,这很好。但是,我需要打开Main以便它知道将哪种类型的IDrawer传递给Pencil. 如果我依赖用户输入,这只是需要做的吗?如果有办法在没有 switch 语句的情况下做到这一点,我很乐意看到它!

class Program
{
    public class Pencil
    {
        private IDraw drawer;

        public Pencil(IDraw iDrawer)
        {
            drawer = iDrawer;
        }

        public void Draw()
        {
            drawer.Draw();
        }
    }

    public interface IDraw
    {
        void Draw();
    }

    public class CircleDrawer : IDraw
    {
        public void Draw()
        {
            Console.Write("()\n");
        }
    }

    public class SquareDrawer : IDraw
    {
        public void Draw()
        {
            Console.WriteLine("[]\n");
        }
    }

    static void Main(string[] args)
    {
        Console.WriteLine("What would you like to draw? 1:Circle or 2:Sqaure");

        int input;
        if (int.TryParse(Console.ReadLine(), out input))
        {
            Pencil pencil = null;

            switch (input)
            {
                case 1:
                    pencil = new Pencil(new CircleDrawer());
                    break;
                case 2:
                    pencil = new Pencil(new SquareDrawer());
                    break;
                default:
                    return;
            }

            pencil.Draw();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    }
}

实施的解决方案如下所示(感谢所有回复的人!)这个解决方案让我明白了使用新的IDraw对象我唯一需要做的就是创建它。

public class Pencil
    {
        private IDraw drawer;

        public Pencil(IDraw iDrawer)
        {
            drawer = iDrawer;
        }

        public void Draw()
        {
            drawer.Draw();
        }
    }

    public interface IDraw
    {
        int ID { get; }
        void Draw();
    }

    public class CircleDrawer : IDraw
    {

        public void Draw()
        {
            Console.Write("()\n");
        }

        public int ID
        {
            get { return 1; }
        }
    }

    public class SquareDrawer : IDraw
    {
        public void Draw()
        {
            Console.WriteLine("[]\n");
        }

        public int ID
        {
            get { return 2; }
        }
    }

    public static class DrawingBuilderFactor
    {
        private static List<IDraw> drawers = new List<IDraw>();

        public static IDraw GetDrawer(int drawerId)
        {
            if (drawers.Count == 0)
            {
                drawers =  Assembly.GetExecutingAssembly()
                                   .GetTypes()
                                   .Where(type => typeof(IDraw).IsAssignableFrom(type) && type.IsClass)
                                   .Select(type => Activator.CreateInstance(type))
                                   .Cast<IDraw>()
                                   .ToList();
            }

            return drawers.Where(drawer => drawer.ID == drawerId).FirstOrDefault();
        }
    }

    static void Main(string[] args)
    {
        int input = 1;

        while (input != 0)
        {
            Console.WriteLine("What would you like to draw? 1:Circle or 2:Sqaure");

            if (int.TryParse(Console.ReadLine(), out input))
            {
                Pencil pencil = null;

                IDraw drawer = DrawingBuilderFactor.GetDrawer(input);

                pencil = new Pencil(drawer); 
                pencil.Draw();
            }
        }
    }
4

5 回答 5

61

策略不是神奇的反转换解决方案。它所做的就是将你的代码模块化,这样就不会把一个大开关和业务逻辑都混在一个维护噩梦中了

  • 您的业​​务逻辑是隔离的并且可以扩展
  • 您可以选择如何创建具体类(例如,参见工厂模式)
  • 您的基础架构代码(您的主要代码)可以非常干净,两者都没有

例如 - 如果你在你的 main 方法中使用了 switch 并创建了一个接受命令行参数并返回 IDraw 实例的类(即它封装了那个 switch)你的 main 再次是干净的并且你的 switch 是在一个唯一目的的类中是实现这一选择。

于 2010-09-30T19:31:20.010 回答
16

以下是针对您的问题的过度设计的解决方案,只是为了避免if/switch陈述。

CircleFactory: IDrawFactory
{
  string Key { get; }
  IDraw Create();
}

TriangleFactory: IDrawFactory
{
  string Key { get; }
  IDraw Create();
}

DrawFactory
{
   List<IDrawFactory> Factories { get; }
   IDraw Create(string key)
   {
      var factory = Factories.FirstOrDefault(f=>f.Key.Equals(key));
      if (factory == null)
          throw new ArgumentException();
      return factory.Create();
   }
}

void Main()
{
    DrawFactory factory = new DrawFactory();
    factory.Create("circle");
}
于 2010-09-30T19:45:16.907 回答
15

我不认为您在演示应用程序中的切换实际上是策略模式本身的一部分,它只是用于练习您定义的两种不同策略。

“开关是一个危险信号”警告是指在策略内部有开关;例如,如果您定义了一个策略“GenericDrawer”,并让它通过一个参数值的开关在内部确定用户是想要 SquareDrawer 还是 CircleDrawer,那么您将无法从策略模式中受益。

于 2010-09-30T19:34:56.853 回答
14

if你也可以在字典的帮助下摆脱

Dictionary<string, Func<IDraw> factory> drawFactories = new Dictionary<string, Func<IDraw> factory>() { {"circle", f=> new CircleDraw()}, {"square", f=> new SquareDraw()}}();

Func<IDraw> factory;
drawFactories.TryGetValue("circle", out factory);

IDraw draw = factory();
于 2010-09-30T19:53:34.520 回答
5

有点晚了,但对于仍然对完全删除条件语句感兴趣的人来说。

     class Program
     {
        Lazy<Dictionary<Enum, Func<IStrategy>>> dictionary = new Lazy<Dictionary<Enum, Func<IStrategy>>>(
            () =>
                new Dictionary<Enum, Func<IStrategy>>()
                {
                    { Enum.StrategyA,  () => { return new StrategyA(); } },
                    { Enum.StrategyB,  () => { return new StrategyB(); } }
                }
            );

        IStrategy _strategy;

        IStrategy Client(Enum enu)
        {
            Func<IStrategy> _func
            if (dictionary.Value.TryGetValue(enu, out _func ))
            {
                _strategy = _func.Invoke();
            }

            return _strategy ?? default(IStrategy);
        }

        static void Main(string[] args)
        {
            Program p = new Program();

            var x = p.Client(Enum.StrategyB);
            x.Create();
        }
    }

    public enum Enum : int
    {
        StrategyA = 1,
        StrategyB = 2
    }

    public interface IStrategy
    {
        void Create();
    }
    public class StrategyA : IStrategy
    {
        public void Create()
        {
            Console.WriteLine("A");
        }
    }
    public class StrategyB : IStrategy
    {
        public void Create()
        {
            Console.WriteLine("B");
        }
    }
于 2018-01-29T13:49:12.763 回答