学习高校课程-软件设计模式-责任链模式和命令模式(lec9)

原文链接

Chain of Responsibility: Problem

Example: an online ordering system
示例:在线订购系统
– The request must pass a series of checks
– New requirements: validation, filtering repeated failed requests, speeding up by returning cached results, and more
– 请求必须通过一系列检查
– 新要求:验证、过滤重复失败的请求、通过返回缓存结果来加速等等

Chain of Responsibility: Solution

The pattern suggests that you link these handlers into a chain. Each linked handler has a field for storing a reference to the next handler in the chain. In addition to processing a request, handlers pass the request further along the chain. The request travels along the chain until all handlers have had a chance to process it.
该模式建议您将这些处理程序链接到一条链中。每个链接的处理程序都有一个字段,用于存储对链中下一个处理程序的引用。除了处理请求之外,处理程序还会沿着链进一步传递请求。请求沿着链传播,直到所有处理程序都有机会处理它

Command: Problem

Before long, you realize that this approach is deeply flawed. First, you have an enormous number of subclasses, and that would be okay if you weren’t risking breaking the code in these subclasses each time you modify the base Button class. Put simply, your GUI code has become awkwardly dependent on the volatile code of the business logic.
不久之后,您就会意识到这种方法存在严重缺陷。首先,您有大量的子类,如果您每次修改Button基类时不会冒破坏这些子类中的代码的风险,那就没问题。简而言之,您的 GUI 代码已经变得笨拙地依赖于业务逻辑的易失性代码。

Command: Solution

Principle of separation of concerns
关注点分离原则

  • Breaking an app into layers
    将应用程序分成多个层
  • Common example: a layer for GUI, and another for business logic
    常见示例:一个用于 GUI 的层,另一个用于业务逻辑

Command (aka Action or Transaction)
命令(又名操作或事务)

  • GUI objects should not send request directly
    GUI 对象不应直接发送请求
  • Extract request details into a separate Command class with a single method that triggers this request
    使用触发此请求的单一方法将请求详细信息提取到单独的 Command 类中

Commands become a convenient middle layer, reducing coupling between the GUI and business logic
命令成为方便的中间层,减少GUI和业务逻辑之间的耦合

Making commands implement the same interface
使命令实现相同的接口

posted @ 2024-10-31 20:30  Mephostopheles  阅读(4)  评论(0编辑  收藏  举报