java设计模式-命令模式

命令模式是一种行为设计模式,它允许将请求封装为对象,使得可以用不同的请求对客户进行参数化。在 Java Swing 中,结合命令模式可以很好地处理按钮点击事件。下面是一个简单的示例,演示如何使用命令模式来处理 Java Swing 中的按钮点击事件:

步骤一:定义命令接口

首先,我们定义一个命令接口 Command,它有一个执行方法 execute()。

java 复制代码
// Command.java
public interface Command {
    void execute();
}

步骤二:创建具体命令类

然后,我们创建具体的命令类,每个类代表一个具体的操作。

java 复制代码
// OpenFileCommand.java
public class OpenFileCommand implements Command {
    private final String filename;

    public OpenFileCommand(String filename) {
        this.filename = filename;
    }

    @Override
    public void execute() {
        // 执行打开文件的操作
        System.out.println("Opening file: " + filename);
        // 实际应用中可以在这里编写打开文件的具体逻辑
    }
}

// SaveFileCommand.java
public class SaveFileCommand implements Command {
    private final String filename;

    public SaveFileCommand(String filename) {
        this.filename = filename;
    }

    @Override
    public void execute() {
        // 执行保存文件的操作
        System.out.println("Saving file: " + filename);
        // 实际应用中可以在这里编写保存文件的具体逻辑
    }
}

步骤三:创建调用者类

接下来,我们创建一个调用者类,用于触发命令执行。

java 复制代码
// ButtonInvoker.java
public class ButtonInvoker {
    private Command command;

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

    public void clickButton() {
        // 模拟按钮点击事件
        command.execute();
    }
}

步骤四:创建 Swing 界面和按钮

现在,我们创建一个简单的 Swing 界面,并添加按钮用于触发命令。

java 复制代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CommandPatternExample extends JFrame {
    private ButtonInvoker invoker = new ButtonInvoker();

    public CommandPatternExample() {
        super("Command Pattern Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);

        JButton openButton = new JButton("Open File");
        openButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Command openCommand = new OpenFileCommand("example.txt");
                invoker.setCommand(openCommand);
                invoker.clickButton();
            }
        });

        JButton saveButton = new JButton("Save File");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Command saveCommand = new SaveFileCommand("example.txt");
                invoker.setCommand(saveCommand);
                invoker.clickButton();
            }
        });

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());
        panel.add(openButton);
        panel.add(saveButton);

        getContentPane().add(panel);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new CommandPatternExample();
            }
        });
    }
}

解释说明

  • 命令接口 Command :定义了所有具体命令类都要实现的 execute() 方法。
  • 具体命令类 :如 OpenFileCommand 和 SaveFileCommand,分别实现了打开文件和保存文件的操作。
  • 调用者类 ButtonInvoker :负责调用命令对象的 execute() 方法。
  • Swing 界面 :在 CommandPatternExample 类中创建了一个简单的 Swing 界面,包含两个按钮,分别用于触发打开文件和保存文件的命令。

在实际应用中,你可以根据需要定义更复杂的命令和操作,并结合更多的 Swing 组件和事件来实现更复杂的用户交互和命令处理逻辑。

相关推荐
三无少女指南1 小时前
从这里开始:Java 后端与 AI 工程的三条阅读路线
java·学习路线·ai工程
香蕉大香蕉(06敬畏市场)1 小时前
MySQL 单点详解(07)
java·数据库·mysql·ai·博客·八股
nice_lcj5202 小时前
深入理解 Java 反射:从 Class 对象到方法调用(含性能实测 + 迷你 IOC 实战 + 面试考点)
java·开发语言·后端·面试
骑着蜗牛撵大象3272 小时前
2026 后端 AI 工程化:Spring AI 管调用、MCP 管工具、Agent 内嵌管自治
java·人工智能·后端·spring·ai·可观测性·mcp
tryxr2 小时前
JVM 垃圾回收机制
java·jvm·gc·垃圾回收
揣一尾游鱼yu3 小时前
Spring上(IOC)笔记
java·笔记·spring·ioc
荣码3 小时前
长上下文与大文档处理:200页PDF怎么喂给AI,我踩了4个坑
java·python
极限挑战哥4 小时前
共享电单车联营平台分账架构实践:二清合规与自动分账零人工方案
java·大数据·人工智能·微信小程序·架构·微信公众平台
皮皮林5514 小时前
比 VMware 更快,更轻的虚拟机,横空出世!
java
Thomas.Sir5 小时前
第13课:MyBatis-Plus整合SpringBoot4.x,分页、条件查询、逻辑删除实战
java·spring boot