[問題] 命令模式的疑問

作者: brian780405 (pohan)   2017-08-24 14:15:50
正常來說命令應該長這樣
public interface Command
{
void Execute();
}
public class Command_1 : Command
{
public Receiver_1 receiver;
public string command;
public Command_1(Receiver_1 receiver, string command)
{
this.receiver = receiver;
this.command = command;
}
public void Execute()
{
receiver.Action(command);
}
}
public class Receiver_1
{
public void Action(string command)
{
//這裡放實作
Console.WriteLine(command);
}
}
==============================================================================
但我的疑問是「直接繼承Command然後實作」不就好了?
像這樣
public class Command_2 : Command
{
private int command;
public Command_2(int command)
{
this.command = command;
}
public void Execute()
{
Console.WriteLine(command);
}
}
是因為實作上比較不直覺嗎?
==============================================================================
有查到一個教學https://goo.gl/mAqyG5
看到他把Receiver裡面實作各種方法
看起來滿方便的,但這樣違反開放封閉原則吧?
所以現在已經有點搞不太懂命令模式為何要Command裡面包Receiver了
而且C#直接用Action好像還比較方便?
作者: Litfal (Litfal)   2017-08-26 17:22:00
每個Command的參數數量不會是一樣的,當然不會繼承同一個唯一規範就是,對於執行者來說,它知道這些東西能被執行Receiver是接受命令的物件,其實就是命令參數的一部份,不是必須,但也不一定是唯一舉個例來說,要對一個TextBox設定某字串,那建立時就會有SetTextBoxCommand(TextBox txtBox, string s)這樣兩個參數必須要設定

Links booklink

Contact Us: admin [ a t ] ucptt.com