命令模式(Command Pattern)和策略模式(Strategy Pattern)是面向对象设计模式中非常实用的两种模式,它们旨在提高代码的灵活性和可扩展性。本文将详细介绍这两种模式的基本概念、实现方法以及在实际开发中的应用。

命令模式

命令模式是一种行为型设计模式,其核心是将请求封装为一个对象,从而允许用户对请求进行参数化、排队或记录请求,以及支持可撤销的操作。

命令模式的基本结构

  1. 命令接口(Command):声明执行操作的接口。
  2. 具体命令(ConcreteCommand):实现接口,定义执行操作的方法。
  3. 调用者(Invoker):负责调用命令对象执行请求。
  4. 接收者(Receiver):负责执行与请求相关的操作。
  5. 客户端(Client):创建一个具体命令对象,并设置其接收者。

实现示例

以下是一个使用Java实现的命令模式示例,用于控制台输出:

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

// 具体命令
class PrintCommand implements Command {
    private String message;

    public PrintCommand(String message) {
        this.message = message;
    }

    @Override
    public void execute() {
        System.out.println(message);
    }
}

// 调用者
class Invoker {
    private Command command;

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

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

// 客户端
public class CommandPatternDemo {
    public static void main(String[] args) {
        Invoker invoker = new Invoker();
        Command printCommand = new PrintCommand("Hello, World!");
        invoker.setCommand(printCommand);
        invoker.invoke();
    }
}

策略模式

策略模式是一种行为型设计模式,它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。

策略模式的基本结构

  1. 策略接口(Strategy):声明所有支持的算法的公共方法。
  2. 具体策略(ConcreteStrategy):实现策略接口,定义所有支持的算法。
  3. 环境类(Context):使用某个具体的策略,维持所有算法的状态。
  4. 客户端(Client):根据需要选择一个算法,并设置到环境类中。

实现示例

以下是一个使用Java实现的策略模式示例,用于计算不同类型的几何图形面积:

// 策略接口
interface ShapeStrategy {
    double calculateArea(double... dimensions);
}

// 具体策略
class CircleStrategy implements ShapeStrategy {
    @Override
    public double calculateArea(double... dimensions) {
        return Math.PI * dimensions[0] * dimensions[0];
    }
}

class RectangleStrategy implements ShapeStrategy {
    @Override
    public double calculateArea(double... dimensions) {
        return dimensions[0] * dimensions[1];
    }
}

// 环境类
class ShapeContext {
    private ShapeStrategy strategy;

    public void setStrategy(ShapeStrategy strategy) {
        this.strategy = strategy;
    }

    public double calculateArea(double... dimensions) {
        return strategy.calculateArea(dimensions);
    }
}

// 客户端
public class StrategyPatternDemo {
    public static void main(String[] args) {
        ShapeContext context = new ShapeContext();
        context.setStrategy(new CircleStrategy());
        System.out.println("Circle Area: " + context.calculateArea(5.0));

        context.setStrategy(new RectangleStrategy());
        System.out.println("Rectangle Area: " + context.calculateArea(5.0, 4.0));
    }
}

总结

命令模式和策略模式都是提高代码灵活性和可扩展性的有效方法。通过将请求和算法封装成对象,我们可以轻松地替换和扩展这些对象,从而降低系统复杂性,提高代码的可维护性。在实际开发中,合理运用这两种模式,可以显著提高代码质量。