Behavioral Patterns - Command Patterns

Command mode (Command)

Troubleshoot command execution issues

describe

Encapsulate a request as an object, and define the execution method of the object, so that the request can be delayed, queued, recorded and revoked. This approach can improve code reusability and maintainability, while also supporting transactional operations.

Applicable environment

Use when you need to encapsulate the request into an object; use when you need to support undo operations.

advantage:

The sender and receiver of the request can be decoupled to improve the flexibility of the system; new commands can be easily extended.

shortcoming:

For too many commands, it will cause the system code to become complicated; the command mode may cause the performance of the system to degrade.

Violation of principles:

Open-closed principle: If you need to add new commands, you need to modify all command classes, which violates this principle.

Code

The bookstore order system needs to save the order information when the customer submits the order.
Now use the traditional way to process the order:

class Book:
    def __init__(self, name, price):
        self.name = name
        self.price = price
    
class Order:
    def __init__(self):
        self.order_items = []

    def add_item(self, item):
        self.order_items.append(item)

    def place_order(self):
        total_price = sum([item.price for item in self.order_items])
        print(f"订单总金额为{total_price}元")

book1 = Book('Python编程从入门到实践', 68.0)
book2 = Book('流畅的Python', 79.0)
order = Order()
order.add_item(book1)
order.add_item(book2)
order.place_order()

The above code has the following problems:

  1. When performing other operations on the order, the original code needs to be modified. Writing different methods for different operations leads to code redundancy.
    This problem can be solved through the command mode, the specific implementation is as follows:
# 创建一个抽象类Command,定义一个抽象方法execute()
# 具体子类需要实现该方法,并通过调用Receiver的相关方法来执行具体操作
from abc import ABC, abstractmethod

class Command(ABC):
    @abstractmethod
    def execute(self):
        pass

# 创建一个具体的Command类,用于保存Order信息class OrderCommand(Command):
    def __init__(self, order):
        self.order = order

    def execute(self):
        total_price = sum([item.price for item in self.order.order_items])
        print(f"订单总金额为{total_price}元")

# 创建一个Receiver类,用于实现具体操作class Order:
    def __init__(self):
        self.order_items = []

    def add_item(self, item):
        self.order_items.append(item)

    def remove_item(self, item):
        self.order_items.remove(item)

    def place_order(self):
        order_command = OrderCommand(self)
        order_command.execute()

book1 = Book('Python编程从入门到实践', 68.0)
book2 = Book('流畅的Python', 79.0)
order = Order()
order.add_item(book1)
order.add_item(book2)
order.place_order()

Guess you like

Origin blog.csdn.net/u010349629/article/details/130031629