1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Command command = new ConcreateCommand(); Receiver receiver = new ConcreateReceiver(); command.SetReceiver(receiver); Invoker invoker = new Invoker(command); invoker.execute(); } } /* Command 他のオブジェクトへのメソッド呼び出しとパラメータをオブジェクト化する。 */ public class Invoker // Commandの呼び出し { private Command command; public Invoker(Command command) { this.command = command; } public void execute() { this.command.Execute(); } } public interface Command //命令 { void SetReceiver(Receiver receiver); void Execute(); } public class ConcreateCommand: Command // 具体的な命令 { Receiver receiver; public void SetReceiver(Receiver receiver) { this.receiver = receiver; } public void Execute() { receiver.Action(); } } public interface Receiver //Commandの受信者 { void Action(); } public class ConcreateReceiver : Receiver //具体的な受信者 { public void Action() { } } } |
ざっくりまとめると、commandにreceiverを渡す。(commandがreceiverを保持)
渡し方は、Command cmd = new ConcreateCommand(receiver)
あるいは、上記のようなSetReceiver(receiver)とか。
そして、commandのExecute()の中でreceiverのAction()を呼ぶ。
Invokerは呼び出しで、そこからcommandのExecute()を呼ぶ。
処理の実体はreceiverのAction()の中。