【问题标题】:Would this be a good case for polymorphism这对多态性来说是一个很好的例子吗
【发布时间】:2008-12-12 11:07:59
【问题描述】:

对不起,如果这是一个非常基本的问题,但我正在努力解决我应该如何解决这个问题。我正在尝试为 OLE 对象包装一些命令,基本规范如下所示:

Set Window window_id
    //Units is part of the position setter.
    [ Position ( x, y ) [ Units paper_units ] ] 
    [ Width win_width [ Units paper_units ] ] 
    [ Height win_height [ Units paper_units ] ]
    ..... this goes on for about 20+ commands, all optional.

[] 之间的任何内容都是可选的。

所以我需要创建一个类,我们称之为“CommandBuilder”,它可以为所有这些可选设置器设置方法,我可以处理,我遇到的主要问题是ToCommandString 方法需要输出一个看起来像这样的字符串:

Set Window 1 Position (x,y) Units "m" Height 100 Units "m" + what ever else the user added

当设置的变量并不复杂或只有几个变量但存在大量变量和/或嵌套值时,只需根据设置的变量执行一些 if 并加入字符串即可也是可选的,如果发生任何变化,它会使 ToString 方法非常长且复杂 + 难以维护。

我想知道是否可以通过使用多态性来解决这个问题。

interface ICommand
{
    string ToCommandString();
}

class PositionCommand : ICommand
{
    double X;
    double Y;
    string Units;

    public PositionCommand(double x, double y)
    {
        this.X = x;
        this.Y = y;
    }

    public PositionCommand(double x,double y, string units)
    {
        this.X = x;
        this.Y = y;
        this.Units = units;
    }

    public string ToCommandString()
    {
        //Add more stuff here to handle empty units.
        return String.Format(" Postion ({0},{1})", X.ToString(), Y.ToString());
    }
}
....more command classes.

然后我在“CommandBuilder”中设置的所有方法都可以创建正确的命令类型并将其添加到列表中,然后“CommandBuilder”方法中的主ToString可以循环通过所有已设置并调用 ToCommandString 的内容,无需担心执行任何 if 语句或空检查。

这是解决这个问题的正确方法吗?

附:如果您需要更多信息,我很乐意补充,只是不想先走太久。

【问题讨论】:

    标签: c# .net polymorphism


    【解决方案1】:

    这对我来说听起来很合理。我肯定会将 ICommand 实例的构造保留在 CommandBuilder 内部:

    class CommandBuilder
    {
      private List<ICommand> _commands = new List<ICommand>();
    
      public CommandBuilder Position(double x, double y)
      {
        _commands.Add(new PositionCommand(x,y))
        return this;
      }
    
      ...
    }
    

    不仅仅是

    class CommandBuilder
    {
      public void AddCommand(ICommand cmd)
      { ... }
    }
    

    【讨论】:

    • 我能问点什么吗?为什么要从 position 函数返回一个 CommandBuilder 对象?
    • 这个想法是,CommandBuilder 提供了一个流畅的接口 (en.wikipedia.org/wiki/Fluent_interface),让您可以以类似于自然语言的结构构建对象。
    【解决方案2】:

    是的。我认为你已经很好地涵盖了它。

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 1970-01-01
      • 2012-06-27
      • 2015-10-30
      • 2011-06-25
      • 2011-02-22
      • 2011-08-14
      • 1970-01-01
      • 2016-04-25
      相关资源
      最近更新 更多