Package ParttenDesign; // Command interface of the general public interface Command {void defend (); void attack ();}
The command action the General wants the soldiers to send
Package ParttenDesign; public class Commander implements Command {Command command Command; public Commander (command Command) {this. command = command ;}@ Overridepublic void attack () {System. out. println ("commander sends attack command"); command. attack () ;}@ Overridepublic void defend () {System. out. println ("the commander issued a defensive command"); command. defend ();}}
The soldiers receive the commands from the generals.
Package ParttenDesign; public class Privates implements Command {@ Overridepublic void attack () {System. out. println ("soldiers receive attack commands and launch attacks"); System. out. println ("-------------------------------------"); System. out. println ("") ;}@ Overridepublic void defend () {System. out. println ("soldiers receive defensive commands, retreat and defend"); System. out. println ("-------------------------------------"); System. out. println ("");}}
Test code:
Package ParttenDesign; public class MyMain {/*** command mode: * (Action sender) the commander sends (defense, attack) (command) commands by calling (Action transmission, (Action recipient) the soldier accepts the Command and then performs the corresponding action * @ param args */public static void main (String [] args) {Command privates = new Privates (); command commander = new Commander (privates); commander. attack (); commander. defend ();}}