命令模式-实例使用

未使用命令模式的UML

命令模式-实例使用_第1张图片

使用命令模式后的UML

命令模式-实例使用_第2张图片

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;
    }
    @Override
    public 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;
    }
    @Override
    public 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;
    }
    @Override
    public 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);
    }
}

命令模式-实例使用_第3张图片

你可能感兴趣的:(命令模式)