python: Command Pattern

python 复制代码
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:命令模式(Command Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/18 21:09
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : JewelCraftsman.py
# explain   : 学习
 
from abc import ABC, abstractmethod
 
 
# -------------------------- 1. 接收者(Receiver):珠宝工匠 --------------------------
class JewelCraftsman(object):
    """
    珠宝工匠(真正执行具体操作的接收者)
    """
 
    def polish_ring(self, ring_type: str):
        """
        抛光戒指
        Args:
            ring_type:
 
        Returns:
 
        """
        print(f"工匠正在抛光 {ring_type} 戒指,使其恢复光泽✨")
 
    def inlay_diamond(self, necklace: str, diamond_size: str):
        """
        给项链镶嵌钻石
        Args:
            necklace:
            diamond_size:
 
        Returns:
 
        """
        print(f"工匠正在给 {necklace} 项链镶嵌 {diamond_size} 钻石💎")
 
    def clean_necklace(self, necklace: str):
        """
        清洗项链
        Args:
            necklace:
 
        Returns:
 
        """
        print(f"工匠正在超声波清洗 {necklace} 项链,去除污渍🧼")
 
 
 
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:命令模式(Command Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/18 21:11
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : JewelCommand.py
# explain   : 学习
 
from abc import ABC, abstractmethod
 
# -------------------------- 2. 命令抽象类(Command) --------------------------
class JewelCommand(ABC):
    """
    珠宝操作命令的抽象基类
    """
 
    @abstractmethod
    def execute(self):
        """
        执行命令
        Returns:
 
        """
        pass
 
    @abstractmethod
    def undo(self):
        """
        撤销命令(可选,增强功能)
        Returns:
 
        """
        pass
python 复制代码
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:命令模式(Command Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/18 21:13
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : PolishRingCommand.py
# explain   : 学习
 
from CommandPattern.JewelCommand import JewelCommand
from CommandPattern.JewelCraftsman import JewelCraftsman
 
# -------------------------- 3. 具体命令(Concrete Command) --------------------------
class PolishRingCommand(JewelCommand):
    """
    抛光戒指的具体命令
    """
 
    def __init__(self, craftsman: JewelCraftsman, ring_type: str):
        """
 
        Args:
            craftsman:
            ring_type:
        """
        # 绑定接收者和命令参数
        self.craftsman = craftsman
        self.ring_type = ring_type
        self.executed = False  # 标记是否已执行
 
    def execute(self):
        """
 
        Returns:
 
        """
        self.craftsman.polish_ring(self.ring_type)
        self.executed = True
 
    def undo(self):
        """
 
        Returns:
 
        """
        if self.executed:
            print(f"撤销操作:停止抛光 {self.ring_type} 戒指🔙")
            self.executed = False
 
 
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:命令模式(Command Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/18 21:15
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : InlayDiamondCommand.py
# explain   : 学习
from CommandPattern.JewelCommand import JewelCommand
from CommandPattern.JewelCraftsman import JewelCraftsman
 
# -------------------------- 3. 具体命令(Concrete Command) --------------------------
 
class InlayDiamondCommand(JewelCommand):
    """
    镶嵌钻石的具体命令
    """
 
    def __init__(self, craftsman: JewelCraftsman, necklace: str, diamond_size: str):
        """
 
        Args:
            craftsman:
            necklace:
            diamond_size:
        """
        self.craftsman = craftsman
        self.necklace = necklace
        self.diamond_size = diamond_size
        self.executed = False
 
    def execute(self):
        """
 
        Returns:
 
        """
        self.craftsman.inlay_diamond(self.necklace, self.diamond_size)
        self.executed = True
 
    def undo(self):
        """
 
        Returns:
 
        """
        if self.executed:
            print(f"撤销操作:取出 {self.necklace} 项链上的 {self.diamond_size} 钻石🔙")
            self.executed = False
 
 
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:命令模式(Command Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/18 21:17
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : CleanNecklaceCommand.py
# explain   : 学习
 
from CommandPattern.JewelCommand import JewelCommand
from CommandPattern.JewelCraftsman import JewelCraftsman
 
# -------------------------- 3. 具体命令(Concrete Command) --------------------------
 
class CleanNecklaceCommand(JewelCommand):
    """
    清洗项链的具体命令
    """
 
    def __init__(self, craftsman: JewelCraftsman, necklace: str):
        """
 
        Args:
            craftsman:
            necklace:
        """
        self.craftsman = craftsman
        self.necklace = necklace
        self.executed = False
 
    def execute(self):
        """
 
        Returns:
 
        """
        self.craftsman.clean_necklace(self.necklace)
        self.executed = True
 
    def undo(self):
        """
 
        Returns:
 
        """
        if self.executed:
            print(f"撤销操作:停止清洗 {self.necklace} 项链🔙")
            self.executed = False
python 复制代码
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:命令模式(Command Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/18 21:18
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : JewelWorkbench.py
# explain   : 学习
 
from CommandPattern.JewelCommand import JewelCommand
from CommandPattern.JewelCraftsman import JewelCraftsman
 
# -------------------------- 4. 调用者(Invoker):珠宝工作台 --------------------------
class JewelWorkbench:
    """珠宝工作台(调用者:负责触发命令执行/撤销)"""
 
    def __init__(self):
        self.current_command = None  # 当前执行的命令
        self.command_history = []  # 命令执行历史(支持批量撤销/回放)
 
    def set_command(self, command: JewelCommand):
        """设置要执行的命令"""
        self.current_command = command
 
    def execute_command(self):
        """执行当前命令"""
        if self.current_command:
            self.current_command.execute()
            self.command_history.append(self.current_command)
            self.current_command = None  # 执行后清空当前命令
        else:
            print("没有可执行的珠宝操作命令❌")
 
    def undo_last_command(self):
        """撤销上一个执行的命令"""
        if self.command_history:
            last_cmd = self.command_history.pop()
            last_cmd.undo()
        else:
            print("没有可撤销的珠宝操作命令❌")
python 复制代码
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:命令模式(Command Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/18 21:20
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : CommandBll.py
# explain   : 学习
 
 
from CommandPattern.PolishRingCommand import PolishRingCommand
from CommandPattern.InlayDiamondCommand import InlayDiamondCommand
from CommandPattern.JewelWorkbench import JewelWorkbench
from CommandPattern.JewelCraftsman import JewelCraftsman
from CommandPattern.CleanNecklaceCommand import CleanNecklaceCommand
 
# -------------------------- 5. 客户端调用示例 --------------------------
 
class CommandBll(object):
    """
 
    """
    def demo(self):
        """
 
        Returns:
 
        """
        # 1. 创建接收者(珠宝工匠)
        craftsman = JewelCraftsman()
 
        # 2. 创建调用者(珠宝工作台)
        workbench = JewelWorkbench()
 
        # 3. 创建具体命令并执行
        print("===== 执行第一个命令:抛光铂金戒指 =====")
        polish_cmd = PolishRingCommand(craftsman, "铂金")
        workbench.set_command(polish_cmd)
        workbench.execute_command()
 
        print("\n===== 执行第二个命令:给黄金项链镶嵌1克拉钻石 =====")
        inlay_cmd = InlayDiamondCommand(craftsman, "黄金", "1克拉")
        workbench.set_command(inlay_cmd)
        workbench.execute_command()
 
        print("\n===== 执行第三个命令:清洗珍珠项链 =====")
        clean_cmd = CleanNecklaceCommand(craftsman, "珍珠")
        workbench.set_command(clean_cmd)
        workbench.execute_command()
 
        # 4. 撤销操作
        print("\n===== 撤销最后一个命令 =====")
        workbench.undo_last_command()
 
        print("\n===== 再次撤销命令 =====")
        workbench.undo_last_command()

调用:

python 复制代码
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/18 20:58
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : main.py
# explain   : 学习
from bll.MementoBll import MementoBll
from bll.CommandBll import CommandBll
 
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
 
    #实现备忘录模式(Memento Pattern)
    #mementobll= MementoBll()
    #mementobll.demo()
    #命令模式(Command Pattern)
    commandBll= CommandBll()
    commandBll.demo()
    print('PyCharm')

输出:

python 复制代码
===== 执行第一个命令:抛光铂金戒指 =====
工匠正在抛光 铂金 戒指,使其恢复光泽✨
 
===== 执行第二个命令:给黄金项链镶嵌1克拉钻石 =====
工匠正在给 黄金 项链镶嵌 1克拉 钻石💎
 
===== 执行第三个命令:清洗珍珠项链 =====
工匠正在超声波清洗 珍珠 项链,去除污渍🧼
 
===== 撤销最后一个命令 =====
撤销操作:停止清洗 珍珠 项链🔙
 
===== 再次撤销命令 =====
撤销操作:取出 黄金 项链上的 1克拉 钻石🔙
相关推荐
Cosmoshhhyyy1 小时前
《Effective Java》解读第41条:用标记接口定义类型
java·开发语言
曲幽2 小时前
FastAPI实战:WebSocket长连接保持与心跳机制,从入门到填坑
javascript·python·websocket·keep-alive·fastapi·heartbeat·connection
锅包一切2 小时前
【蓝桥杯JavaScript基础入门】一、JavaScript基础
开发语言·前端·javascript·蓝桥杯
前路不黑暗@2 小时前
Java项目:Java脚手架项目的 B 端用户服务(十四)
android·java·开发语言·spring boot·笔记·学习·spring cloud
好学且牛逼的马3 小时前
从“混沌初开”到“有序统一”:Java集合框架发展历程与核心知识点详解
前端·数据库·python
wuqingshun3141593 小时前
什么是浅拷贝,什么是深拷贝,如何实现深拷贝?
java·开发语言·jvm
a1117763 小时前
快速制作 虚拟形象项目 MotionPNGTuber
python·live2d
一切尽在,你来3 小时前
AI大模型应用开发前置知识:Python迭代器和生成器深入详解
python·langchain·ai编程