设计模式:命令模式示例

博客介绍了命令模式在软件开发中的应用场景及代码实现。如文本编辑器中用命令模式封装编辑操作以支持撤销和重做;智能家居控制系统将设备操作封装成命令。体现了命令模式的可扩展性和灵活性,可依场景设计不同命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

命令模式在软件开发中有许多应用场景。以下是一些示例及其代码实现:

示例1:文本编辑器的撤销/重做功能

在文本编辑器中,用户执行的编辑操作(如插入、删除文本)可以通过命令模式进行封装,以支持撤销和重做功能。

// Command接口
public interface Command {
    void execute();
    void undo();
}

// Receiver
public class TextFile {
    private StringBuilder text = new StringBuilder();

    public void addText(String text) {
        this.text.append(text);
    }

    public void deleteLast() {
        if (this.text.length() > 0) {
            this.text.deleteCharAt(this.text.length() - 1);
        }
    }

    public String getText() {
        return text.toString();
    }
}

// ConcreteCommand
public class AddTextCommand implements Command {
    private TextFile textFile;
    private String textToAdd;

    public AddTextCommand(TextFile textFile, String textToAdd) {
        this.textFile = textFile;
        this.textToAdd = textToAdd;
    }

    @Override
    public void execute() {
        textFile.addText(textToAdd);
    }

    @Override
    public void undo() {
        for (int i = 0; i < textToAdd.length(); i++) {
            textFile.deleteLast();
        }
    }
}

// Invoker
public class CommandManager {
    private Stack<Command> commandStack = new Stack<>();

    public void executeCommand(Command command) {
        command.execute();
        commandStack.push(command);
    }

    public void undo() {
        if (!commandStack.isEmpty()) {
            Command command = commandStack.pop();
            command.undo();
        }
    }
}

// Client
public class Editor {
    public static void main(String[] args) {
        TextFile textFile = new TextFile();
        CommandManager commandManager = new CommandManager();

        Command addTextCommand = new AddTextCommand(textFile, "Hello ");
        commandManager.executeCommand(addTextCommand);

        addTextCommand = new AddTextCommand(textFile, "World!");
        commandManager.executeCommand(addTextCommand);

        System.out.println("Text: " + textFile.getText()); // Output: "Hello World!"

        commandManager.undo();
        System.out.println("After undo: " + textFile.getText()); // Output: "Hello "

        commandManager.undo();
        System.out.println("After undo: " + textFile.getText()); // Output: ""
    }
}

示例2:智能家居控制系统

智能家居控制系统中,可以将每个设备的操作封装成命令,如打开灯光、调节温度等。

// Command接口
public interface Command {
    void execute();
}

// Receiver
public class Light {
    public void on() {
        System.out.println("Light is on");
    }

    public void off() {
        System.out.println("Light is off");
    }
}

public class Thermostat {
    public void setTemperature(int temperature) {
        System.out.println("Temperature set to " + temperature + " degrees");
    }
}

// ConcreteCommand
public class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.on();
    }
}

public class SetTemperatureCommand implements Command {
    private Thermostat thermostat;
    private int temperature;

    public SetTemperatureCommand(Thermostat thermostat, int temperature) {
        this.thermostat = thermostat;
        this.temperature = temperature;
    }

    @Override
    public void execute() {
        thermostat.setTemperature(temperature);
    }
}

// Invoker
public class SmartHomeControl {
    private Command command;

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

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

// Client
public class SmartHome {
    public static void main(String[] args) {
        Light livingRoomLight = new Light();
        Thermostat thermostat = new Thermostat();
        SmartHomeControl control = new SmartHomeControl();

        Command lightOn = new LightOnCommand(livingRoomLight);
        Command setTemperature = new SetTemperatureCommand(thermostat, 22);

        control.setCommand(lightOn);
        control.pressButton(); // Output: "Light is on"

        control.setCommand(setTemperature);
        control.pressButton(); // Output: "Temperature set to 22 degrees"
    }
}

这些示例展示了命令模式的广泛应用。你可以根据具体的应用场景来设计和实现不同的命令。在命令模式中,可以很容易地添加新的命令,而不影响现有代码,这体现了设计模式的可扩展性和灵活性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值