为了用户使用方便,某系统提供了一系列功能键,用户可以自定义功能键的功能,如功能键FunctionButton可以用于退出系统(SystemExitClass),也可以用于打开帮助界面(DisplayHelpClass)。用户可以通过修改配置文件来改变功能键的用途,现使用命令模式来设计该系统,使得功能键类与功能类之间解耦,相同的功能键可以对应不同的功能。
在这里插入图片描述
类图:
在这里插入图片描述代码:
抽象命令类:

public interface Command {
    public void execute();
}

具体命令类:
1.ExitCommand类:

public class ExitCommand implements Command {
    private SystemExitClass sec;

    public ExitCommand() {
         sec=new SystemExitClass();
    }

    @Override
    public void execute() {
        sec.exit();
    }
}

2.HelpCommand类:

public class HelpCommand implements Command {
    private DisplayHelpClass dhc;

    public HelpCommand() {
        dhc=new DisplayHelpClass();
    }

    @Override
    public void execute() {
        dhc.help();
    }
}

调用者:

public class FunctionButton {
    private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void click(){
        command.execute();
    }
}

接收者:
1.DisplayHelpClass类:

public class DisplayHelpClass {
    public void help(){
        System.out.println("打开帮助界面");
    }
}

2.SystemExitClass类

public class SystemExitClass {
    public void exit(){
        System.out.println("退出系统");
    }
}

客户类:

public class Client {
    public static void main(String[] args) {
        FunctionButton fb=new FunctionButton();
        Command exitCommand=new ExitCommand();
        fb.setCommand(exitCommand);
        fb.click();

        FunctionButton fb1=new FunctionButton();
        Command helepCommand=new HelpCommand();
        fb.setCommand(helepCommand);
        fb.click();
    }

运行结果:
在这里插入图片描述
求关注,求关注,求关注!!!
可以直接问我要代码

在这里插入图片描述

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐