命令模式(3)-宏命令
一个具体命令包含一个其他命令的集合
数字接受者: package DesignPatterns.CommandMode2; import java.util.Random; public class PrintNumber { public void printNumber() { Random random=new Random(10); int a=random.nextInt(); System.out.println("number:"+a); } } 语言接受者: package DesignPatterns.CommandMode2; public class PrintLetter { public void printEnglish() { String eng="English"; System.out.println(eng); } public void printRussian() { String russian="Ж жЗ з Z 兹И и I 伊"; System.out.println(russian); } } 命令接口: package DesignPatterns.CommandMode2; public interface Command { void execute(); } 英文具体命令: package DesignPatterns.CommandMode2; public class PrintEnglishCommand implements Command{ private PrintLetter printLetter; public PrintEnglishCommand(PrintLetter printLetter) { this.printLetter=printLetter; } @Override public void execute() { printLetter.printEnglish(); } } 俄文具体命令: package DesignPatterns.CommandMode2; public class PrintRussianCommand implements Command { private PrintLetter printLetter; public PrintRussianCommand(PrintLetter printLetter) { this.printLetter=printLetter; } @Override public void execute() { printLetter.printRussian(); } } 数字具体命令: package DesignPatterns.CommandMode2; public class PrintEvenNumberCommand implements Command { private PrintNumber printNumber; public PrintEvenNumberCommand(PrintNumber printNumber) { this.printNumber=printNumber; } @Override public void execute() { printNumber.printNumber(); } } 宏命令(包含英文命令,俄文命令,数字命令的集合) package DesignPatterns.CommandMode2; import java.util.ArrayList; public class MacroCommand implements Command { private ArrayList<Command> arrayList; public MacroCommand(ArrayList<Command> arrayList) { this.arrayList=arrayList; } @Override public void execute() { for (int i=0;i<arrayList.size();i++) { Command command=arrayList.get(i); command.execute(); } } } 请求者: package DesignPatterns.CommandMode2; public class RequestMakedir { private Command command; public void setCommand(Command command) { this.command=command; } public void executeCommand() { command.execute(); } } 测试类: package DesignPatterns.CommandMode2; import java.util.ArrayList; public class Application { public static void main(String[] args) { ArrayList<Command> arrayList=new ArrayList<>(); Command command1=new PrintEnglishCommand(new PrintLetter()); Command command2=new PrintRussianCommand(new PrintLetter()); Command command3=new PrintEvenNumberCommand(new PrintNumber()); arrayList.add(command1); arrayList.add(command2); arrayList.add(command3); Command macroCommand=new MacroCommand(arrayList); RequestMakedir requestMakedir=new RequestMakedir(); requestMakedir.setCommand(macroCommand); requestMakedir.executeCommand(); } }