Sha*_*ant 1 c# design-patterns
我正在创建一个应用程序,用户可以设置一系列在对象上运行的函数(图像处理的东西).
每个不同的函数都没有可配置的选项,或者它自己的唯一选项集.
这很难解释,所以让我举一个简单的例子:
问题是我需要允许用户创建一系列自定义清理函数,这些函数将用于批量处理图像.
最好的方法是什么?
我强烈建议您查看命令模式:
本质上,这涉及为用户可以执行的每种操作类型创建"Command"子类 - 并在命令执行后将它们推送到堆栈.
每个命令都知道如何"做"自己,也"撤消"自己.
因此,undo是一个从堆栈中弹出命令并在其上调用undo方法的相对简单的过程.
因为Command的每个实例都可以包含它自己的状态("options"),所以您可以提前创建要使用的命令,并"批处理"它们以获得您要查找的结果.
伪代码:
public class ImageEditor
{
public Stack<Command> undoList = new Stack<Command>();
public void executeCommand(Command command)
{
command.performAction(this);
undoList.push(command);
}
public void undo()
{
undoList.peek().undoAction(this);
undoList.pop();
}
}
public interface ICommand
{
void performAction(ImageEditor editor);
void undoAction(ImageEditor editor);
}
public class CreateBorderCommand : ICommand
{
public int BorderWidth { get; set; }
private Border MyBorderBox { get; set; }
public void performAction(ImageEditor editor)
{
MyBorderBox = new Border(BorderWidth, editor.frame);
editor.addElement(MyBorderBox);
}
public void undoAction(ImageEditor editor)
{
editor.removeElement(MyBorderBox);
}
}
Run Code Online (Sandbox Code Playgroud)
稍后的:
ImageEditor editor = new ImageEditor();
editor.executeCommand(new CreateBorderCommand() { BorderWidth = 10 });
...
Run Code Online (Sandbox Code Playgroud)
如果你真的想要,你可以让它更复杂一些,并使所有命令定义可序列化 - 允许你创建它们的列表并读入列表并稍后执行它们.