抱歉,如果这是一个非常基本的问题,但我正在努力解决我应该如何解决这个问题。我正在尝试为 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 语句或空检查。
这是解决这个问题的正确方法吗?
PS如果您需要更多信息,我很乐意补充,只是不想让它先走太久。