未使用命令模式的UML
使用命令模式后的UML
public abstract class Command {public abstract void execute();
}
public class Invoker {private Command command;/*** 为功能键注入命令* @param command*/public void setCommand(Command command) {this.command = command;}/*** 点击按钮事件*/public void click() {System.out.print("点击按钮事件:");command.execute();}
}
public class BarCommand extends Command{final private BarCodeActivity barCodeActivity;final private Context context;final private String str;public BarCommand(Context context, String str){barCodeActivity = new BarCodeActivity();this.str = str;this.context = context;}@Overridepublic void execute() {barCodeActivity.printBarCode(context,str);}
}
public class LabelCommand extends Command{final private LabelActivity labelActivity;final private Context context;final private String str;public LabelCommand(Context context, String str){labelActivity = new LabelActivity();this.str = str;this.context = context;}@Overridepublic void execute() {labelActivity.printLabel(context,str);}
}
public class QrCommand extends Command{final private QrActivity qrActivity;final private Context context;final private String str;public QrCommand(Context context, String str){qrActivity = new QrActivity();this.str = str;this.context = context;}@Overridepublic void execute() {qrActivity.printQrCode(context,str);}
}
public void onQrcode(View view){Logs.d(TAG,"");Command command = CommandFactory.createQrCommand(getApplicationContext(), mEditText.getText().toString());executeCommand(command);}public void onBarcode(View view){Command command = CommandFactory.createBarCommand(getApplicationContext(), mEditText.getText().toString());executeCommand(command);}public void onLabel(View view){Command command = CommandFactory.createLabelCommand(getApplicationContext(), mEditText.getText().toString());executeCommand(command);}
public class CommandFactory {public static Command createQrCommand(Context context, String data) {return new QrCommand(context, data);}public static Command createBarCommand(Context context, String data) {return new BarCommand(context, data);}public static Command createLabelCommand(Context context, String data) {return new LabelCommand(context, data);}
}