嘗試命令模式的修改:
public abstract class ToolStripItemCommand
{
private bool enabled = true;
private bool visible = true;
private readonly List<ToolStripItem> controls;
protected ToolStripItemCommand()
{
controls = new List<ToolStripItem>();
}
public void RegisterControl(ToolStripItem item, string eventName)
{
item.Click += delegate { Execute(); };
controls.Add(item);
}
public bool Enabled
{
get { return enabled; }
set
{
enabled = value;
foreach (ToolStripItem item in controls)
item.Enabled = value;
}
}
public bool Visible
{
get { return visible; }
set
{
visible = value;
foreach (ToolStripItem item in controls)
item.Visible = value;
}
}
protected abstract void Execute();
}
你這個命令的實現可以以支持你的觀點的狀態是有狀態的。這也使得能夠在你的表單中建立「撤銷」。這裏的消耗這部分玩具代碼:
private ToolStripItemCommand fooCommand;
private void wireUpCommands()
{
fooCommand = new HelloWorldCommand();
fooCommand.RegisterControl(fooToolStripMenuItem, "Click");
fooCommand.RegisterControl(fooToolStripButton, "Click");
}
private void toggleEnabledClicked(object sender, EventArgs e)
{
fooCommand.Enabled = !fooCommand.Enabled;
}
private void toggleVisibleClicked(object sender, EventArgs e)
{
fooCommand.Visible = !fooCommand.Visible;
}
HelloWorldCommand:
public class HelloWorldCommand : ToolStripItemCommand
{
#region Overrides of ControlCommand
protected override void Execute()
{
MessageBox.Show("Hello World");
}
#endregion
}
這是不幸的控制和ToolStripItem的不共享一個通用的接口,因爲它們都具有「啓用」和「可見」屬性。爲了支持這兩種類型,你必須爲兩者合成一個命令,或者使用反射。這兩種解決方案都侵犯了簡單繼承提供的優雅。
@Xline請不要隨意向人們問這樣的問題 - 不適合使用註釋 – Flexo 2014-11-20 09:53:53