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克拉 钻石🔙
相关推荐
番茄去哪了2 小时前
任务调度功能实现
java·开发语言·spring boot
CoberOJ_2 小时前
(2026-04-01更新)小白自己写,量化回测系统stock-quant(六)
python·ai·股票·量化·交易·回测·a股港股美股
qq_283720052 小时前
Python:time/datetime 模块教程
python·时间·模块·日期
Beginner x_u2 小时前
前端八股整理|JavaScript|高频小题 01
开发语言·前端·javascript
_MyFavorite_2 小时前
JAVA重点基础、进阶知识及易错点总结(15)缓冲流 + 转换流
java·开发语言·spring boot
qq_252614413 小时前
PyMySQL 对 caching_sha2_password 支持不完善
python
qq_283720053 小时前
Python教程: sys模块入门学习
python·sys
摇滚侠3 小时前
JAVA 项目教程《苍穹外卖-11》,微信小程序项目,前后端分离,从开发到部署
java·开发语言·微信小程序
瑶总迷弟3 小时前
Python入门第6章:字典(键值对数据结构)
java·数据结构·python
第一程序员3 小时前
Python游戏开发:从入门到实践
python·github