策略模式和命令模式的区别

发布于 2024-10-15 00:42:19 字数 188 浏览 9 评论 0原文

策略模式命令模式?我也在寻找一些 Java 的例子。

What is the difference between the Strategy pattern and the Command pattern? I am also looking for some examples in Java.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

森罗 2024-10-22 00:42:20

通常,命令模式用于根据需要完成的事情创建一个对象 - 获取操作及其参数并将它们包装在要记录的对象中,保存以进行撤消,发送到随着时间的推移,往往会有大量不同的命令对象通过系统中的给定点,并且命令对象将保存描述所请求的操作的不同参数。

另一方面,策略模式用于指定应该如何完成某些事情,并插入到更大的对象或方法中以提供特定的算法。排序策略可能是合并排序,可能是插入排序,或者可能是更复杂的策略,例如仅在列表大于某个最小大小时才使用合并排序。策略对象很少受到命令对象那样的大规模改组,而是经常用于配置或调整目的。

这两种模式都涉及将单个操作的代码和可能的参数从包含它们的原始类中分解到另一个对象中,以提供独立的可变性。差异在于实践中遇到的用例以及每个模式背后的意图。

Typically the Command pattern is used to make an object out of what needs to be done -- to take an operation and its arguments and wrap them up in an object to be logged, held for undo, sent to a remote site, etc. There will tend to be a large number of distinct Command objects that pass through a given point in a system over time, and the Command objects will hold varying parameters describing the operation requested.

The Strategy pattern, on the other hand, is used to specify how something should be done, and plugs into a larger object or method to provide a specific algorithm. A Strategy for sorting might be a merge sort, might be an insertion sort, or perhaps something more complex like only using merge sort if the list is larger than some minimum size. Strategy objects are rarely subjected to the sort of mass shuffling about that Command objects are, instead often being used for configuration or tuning purposes.

Both patterns involve factoring the code and possibly parameters for individual operations out of the original class that contained them into another object to provide for independent variability. The differences are in the use cases encountered in practice and the intent behind each pattern.

迟月 2024-10-22 00:42:20

另一个答案中已经给出了单词。这是具体代码的区别。

public class ConcreteStrategy implements BaseStrategy {

    @Override
    public void execute(Object argument) {

        // Work with passed-in argument.

    }

}

public class ConcreteCommand implements BaseCommand {

    private Object argument;

    public ConcreteCommand(Object argument) {
        this.argument = argument;
    }

    @Override
    public void execute() {

        // Work with own state.

    }

}

Words are already given in the other answer. Here is the difference in concrete code.

public class ConcreteStrategy implements BaseStrategy {

    @Override
    public void execute(Object argument) {

        // Work with passed-in argument.

    }

}

public class ConcreteCommand implements BaseCommand {

    private Object argument;

    public ConcreteCommand(Object argument) {
        this.argument = argument;
    }

    @Override
    public void execute() {

        // Work with own state.

    }

}
我很坚强 2024-10-22 00:42:20

策略 - 快速排序或合并排序 [算法更改]

命令 - 打开或关闭 [操作更改]

Strategy - Quicksort or Mergesort [algo change]

Command - Open or Close [action change]

他不在意 2024-10-22 00:42:20

主要区别在于,该命令对对象执行一些操作。
它可能会改变对象的状态。

而Strategy决定如何处理对象。
它封装了一些业务逻辑。

The main difference is , the command does some action over the object.
It may change the state of an object.

While Strategy decides how to process the object.
It encapsulates some business logic.

吻安 2024-10-22 00:42:20

当给定功能有多个实现(算法)并且您希望根据参数类型在运行时更改算法时,策略模式非常有用。

策略模式的显着特征

  1. 它是一种行为模式
  2. 它基于委托
  3. 它通过修改方法行为来改变对象的内部结构
  4. 它用于在算法系列之间进行切换
  5. 它在运行时改变对象的行为

策略模式的真实示例

命令< /em> 模式用于启用调用者和接收者之间的松耦合。 Command、ConcreteCommand、Receiver、Invoker 和 Client 是该模式的主要组件。

不同的Receiver会通过Invoker & 执行相同的Command。具体命令,但命令的实现在每个接收器中会有所不同。

例如,您必须为电视和电视实现“开”和“关”功能。 DVD播放器。但 TV 和 DVDPlayer 对这些命令的实现方式不同。

请查看以下带有代码示例的帖子:

使用命令设计模式

Strategy pattern is useful when you have multiple implementations (algorithms) for a given feature and you want to change the algorithm at runtime depending on parameter type.

Salient features of Strategy pattern

  1. It's a behavioural pattern
  2. It's based on delegation
  3. It changes guts of the object by modifying method behaviour
  4. It's used to switch between family of algorithms
  5. It changes the behaviour of the object at run time

Real World Example of the Strategy Pattern

Command pattern is used to enable loose coupling between Invoker and Receiver. Command, ConcreteCommand, Receiver, Invoker and Client are major components of this pattern.

Different Receivers will execute same Command through Invoker & Concrete Command but the implementation of Command will vary in each Receiver.

e.g. You have to implement "On" and "Off" functionality for TV & DVDPlayer. But TV and DVDPlayer will have different implementation for these commands.

Have a look at below posts with code examples :

Using Command Design pattern

无戏配角 2024-10-22 00:42:20

我认为这里的一个很大的区别是,当您需要在实现相同接口的不同对象之间进行切换时,使用策略模式相同接口,但是 >命令模式用于在一些实现不同接口的对象之间进行调整(因为它将它们封装到称为“命令对象”的其他对象中)并传递这些命令对象就像策略模式一样。

I think a big difference here is that Strategy pattern is used when you need to shuffle between different objects that implement the same interface, but Command Pattern is used to shuffle between some objects that implement different interfaces ( as it encapsulates them into other objects called "Command Objects" ) and pass these command objects just like Strategy pattern does.

坏尐絯℡ 2024-10-22 00:42:20

策略模式可能的解决方案之一

@Service
@RequiredArgsConstructor
public class StrategyService {

  private final FirstWay firstWay;
  private final SecondWay secondWay;

  private final Map<Operation, Strategy> strategies = new HashMap<>();

  @FunctionalInterface
  interface Strategy {
    Message execute(Entity entity);
  }

  @PostConstruct
  private void init() {
    strategies.put(
        Operation.FIRST_STRATEGY,
        entity ->
            firstWay.process(entity.getId()));
    strategies.put(
        Operation.SECOND_STRATEGY,
        entity ->
            secondWay.process(entity.getId()));
  }

  public Message execute(Entity entity) {
    Strategy strategy = strategies.get(entity.getOperation());

    if (Objects.isNull(strategy)) {
      throw new TechnicalException(
              TechnicalException.NO_STRATEGY_OPERATION);
    }
    return strategy.execute(entity);
  }
}

The one of possible solutions for strategy pattern

@Service
@RequiredArgsConstructor
public class StrategyService {

  private final FirstWay firstWay;
  private final SecondWay secondWay;

  private final Map<Operation, Strategy> strategies = new HashMap<>();

  @FunctionalInterface
  interface Strategy {
    Message execute(Entity entity);
  }

  @PostConstruct
  private void init() {
    strategies.put(
        Operation.FIRST_STRATEGY,
        entity ->
            firstWay.process(entity.getId()));
    strategies.put(
        Operation.SECOND_STRATEGY,
        entity ->
            secondWay.process(entity.getId()));
  }

  public Message execute(Entity entity) {
    Strategy strategy = strategies.get(entity.getOperation());

    if (Objects.isNull(strategy)) {
      throw new TechnicalException(
              TechnicalException.NO_STRATEGY_OPERATION);
    }
    return strategy.execute(entity);
  }
}
幽梦紫曦~ 2024-10-22 00:42:20

Command 更改接收者对象,但将其视为黑盒,调用其方法。

策略是进入接收对象内部的钩子。其主要目的是修改其方法的行为。该方法“从内部”调用它。

在现代语言中,Strategy 通常可以用匿名函数代替。

Command changes a receiver object but treats it as a black box, calling methods on it.

Strategy is a hook into the receiving object's guts. Its main purpose is to modify the behavior of its method. The method invokes it "from within".

In modern languages, Strategy can often be replaced by an anonymous function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文