这个command pattern 貌似用处还挺多的,而且也算是比教复杂的pattern 了,anyway ,直接上代码。
一个简单的代码如下:
-
package CommandPattern;
-
-
//Command interface with an execute() method
-
-
interface Command{
-
public void execute();
-
}
-
-
//Lunch is a receiver
-
class Lunch{
-
public void makeLunch(){
-
System.out.println("Lunch is being made");
-
}
-
}
-
-
//LunchCommand implements Command, it contains a reference to Lunch,a receiver
-
// Its execute() method invokes the appropriate action on the receiver
-
-
class LunchCommand implements Command{
-
Lunch lunch;
-
-
-
public LunchCommand(Lunch lunch){
-
this.lunch = lunch;
-
}
-
-
@Override
-
public void execute(){
-
lunch.makeLunch();
-
}
-
}
-
-
//Dinner is also receiver
-
class Dinner{
-
public void makeDinner(){
-
System.out.println("Dinner is being made");
-
}
-
}
-
-
-
/* The DinnerCommand is similar to LunchCommand.
-
* it contains a reference to Dinner, a receiver.
-
* Its execute() method invokes the makeDinner() action of the Dinner object
-
*/
-
-
class DinnerCommand implements Command{
-
Dinner dinner;
-
-
public DinnerCommand(Dinner dinner){
-
this.dinner = dinner;
-
}
-
-
@Override
-
public void execute(){
-
dinner.makeDinner();
-
}
-
}
-
-
/* MealInvoker is the invoker class, it contains a reference to the Command
-
* to invoke . Its invoke() method calls the execute() method of the Command
-
*/
-
-
class MealInvoker{
-
Command command;
-
-
public MealInvoker(Command command){
-
this.command = command;
-
}
-
-
public void setCommand(Command command){
-
this.command = command;
-
}
-
-
public void invoke(){
-
command.execute();
-
}
-
}
-
-
-
public class CommandPatternDemo {
-
public static void main(String[] args){
-
Lunch lunch = new Lunch(); //receiver
-
Command lunchCommand = new LunchCommand(lunch); //concrete command
-
-
Dinner dinner = new Dinner();
-
Command dinnerCommand = new DinnerCommand(dinner); //concrete command
-
-
MealInvoker mi = new MealInvoker(lunchCommand); //invoker
-
mi.invoke();
-
-
mi.setCommand(dinnerCommand);
-
mi.invoke();
-
}
-
}
下面这个要稍微复杂些了
参考了这个代码:
阅读(930) | 评论(0) | 转发(0) |