banner
Jul 21, 2023
105 Views

Command pattern

Written by
banner

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

Trong lập trình hướng đối tượng, command pattern là một mẫu thiết kế hành vi trong đó một đối tượng được sử dụng để đóng gói tất cả thông tin cần thiết để thực hiện một hành động hoặc kích hoạt một sự kiện vào một thời điểm sau này. Thông tin này bao gồm tên phương thức, đối tượng sở hữu phương thức và các giá trị cho các tham số của phương thức.

Ví dụ: trong ngữ cảnh của một hệ thống đơn giản quản lý các tác vụ (tasks) với khả năng undo/ redo

from abc import ABC, abstractmethod

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

    @abstractmethod
    def undo(self):
        pass

# Receiver
class TaskManager:
    def __init__(self):
        self.tasks = []

    def add_task(self, task):
        self.tasks.append(task)

    def remove_task(self, task):
        self.tasks.remove(task)

    def display_tasks(self):
        print("Tasks:")
        for task in self.tasks:
            print(task)

# Concrete command classes
class AddTaskCommand(Command):
    def __init__(self, task_manager, task):
        self.task_manager = task_manager
        self.task = task

    def execute(self):
        self.task_manager.add_task(self.task)

    def undo(self):
        self.task_manager.remove_task(self.task)

class RemoveTaskCommand(Command):
    def __init__(self, task_manager, task):
        self.task_manager = task_manager
        self.task = task

    def execute(self):
        self.task_manager.remove_task(self.task)

    def undo(self):
        self.task_manager.add_task(self.task)

# Invoker
class TaskInvoker:
    def __init__(self):
        self.command_stack = []

    def execute(self, command):
        command.execute()
        self.command_stack.append(command)

    def undo_last(self):
        if self.command_stack:
            command = self.command_stack.pop()
            command.undo()

if __name__ == "__main__":
    task_manager = TaskManager()
    task_invoker = TaskInvoker()

    task1 = "Complete Project A"
    task2 = "Submit Report"
    task3 = "Prepare Presentation"

    add_task1_command = AddTaskCommand(task_manager, task1)
    add_task2_command = AddTaskCommand(task_manager, task2)
    add_task3_command = AddTaskCommand(task_manager, task3)

    task_invoker.execute(add_task1_command)  # Adds task1 to the list
    task_invoker.execute(add_task2_command)  # Adds task2 to the list
    task_invoker.undo_last()                # Undo adding task2
    task_invoker.execute(add_task3_command)  # Adds task3 to the list

    task_manager.display_tasks()
    # Output:
    # Tasks:
    # Complete Project A
    # Prepare Presentation
Article Categories:
Uncategorized
banner

Leave a Reply

Your email address will not be published. Required fields are marked *