I. Overview
Command mode
Second, the Code
1.client.java
1 Public class Client {2 3 Public void request (server server) {4 server.addcommand (new Textcommand ()); 5 Server.addcommand (new Imagecommand ()); 6 server.dosomething (); 7 }8 }
2.server.java
1 Public classServer {2 3 Privatelist<command> commands =NewArraylist<command>();4 5 Public voiddosomething () {6 for(Command c:commands) {7 C.execute ();8 }9 }Ten One Public voidaddcommand (Command command) { A commands.add (command); - } - the}
3.command.java
1 Public Abstract class Command {2 3 Public Abstract void execute (); 4 Public Abstract void unDo (); 5 6 }
4.textcommand.java
1 Public classTextcommandextendsCommand {2 3 @Override4 Public voidExecute () {5System.out.println ("Textcommand ...."));6 }7 8 @Override9 Public voidUnDo () {Ten //History of operations involved One } A -}
5.imagecommand.java
1 Public classImagecommandextendsCommand {2 3 @Override4 Public voidExecute () {5System.out.println ("Imagecommand ...."));6 }7 8 @Override9 Public voidUnDo () {Ten //History of operations involved One } A -}
6.test.java
1 Public class Test {2 3 @org. Junit.test4 Public void Test () {5 New Client (); 6 C.request (new Server ()); 7 }89 }
Iii. Results of operation
java-Horse Soldier Design Mode learning notes-command mode