Abstract class Command
{
public abstract void Excute ();
}
Class Attackcommand extends Command
{
Soldier Soldier=null;
Public Attackcommand (Soldier Soldier)
{
This.soldier=soldier;
}
public void Excute ()
{
Soldier.attack ();
}
}
Class Defendcommand extends Command
{
Soldier Soldier=null;
Public Defendcommand (Soldier Soldier)
{
This.soldier=soldier;
}
public void Excute ()
{
Soldier.defend ();
}
}
Class Soldier
{
public void Attack ()
{
SYSTEM.OUT.PRINTLN ("Soldier Attack");
}
public void Defend ()
{
System.out.println ("Soldier Defend");
}
}
Class Lord
{
command command;
public void SetCommand (Command command)
{
This.command=command;
}
public void Start ()
{
Command.excute ();
}
}
public class Commandpatterntest
{
public static void Main (string[] args)
{
Soldier asoldier=new Soldier ();
Command acommand=new Attackcommand (asoldier);
Lord Alord=new ();
Alord.setcommand (Acommand);
Alord.start ();
Acommand=new Defendcommand (Asoldier);
Alord.setcommand (Acommand);
Alord.start ();
}
}
/////////////////////////////////////////
Output Result:
Soldier attack
Soldier defend
11 of 23 Design Patterns in Java-command pattern