蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

命令:每次执行的快照与撤销分支:独立运行与结果核对

PYTHONWindows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Pythonpython-command.py
python-command.py57 行
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *

def command(c,out):
    receiver=ModelReceiver({"power":True,"volume":50});history=CommandHistory(receiver)
    power_on=ActionCommand(receiver,lambda state:dict(state,power=True),"on")
    history.execute(power_on);history.undo();c.eq("undo on already-on restores true not false",receiver.state["power"],True)
    volume_up=ActionCommand(receiver,lambda state:dict(state,volume=min(100,state["volume"]+10)),"up")
    history.execute(volume_up);history.execute(volume_up);c.eq("reused command captures separate executions",receiver.state["volume"],70)
    history.undo();c.eq("undo second step",receiver.state["volume"],60);history.undo();c.eq("undo first step",receiver.state["volume"],50)
    history.redo();c.eq("redo actual stored result",receiver.state["volume"],60)
    history.execute(power_on);c.eq("new action clears redo branch",history.redo(),False)
    before=deepcopy(receiver.state);count=len(history.done)
    def fail(state):state["volume"]=99;raise ValueError("controlled command failure")
    c.raises("failed command",ValueError,lambda:history.execute(ActionCommand(receiver,fail,"bad")))
    c.eq("failed command no state mutation",receiver.state,before);c.eq("failed command no history",len(history.done),count)
    guarded=ActionCommand(receiver,lambda state:state,"guarded",guard=lambda state:False)
    c.eq("can_execute explicit contract",guarded.can_execute(),False);c.raises("guard enforced",RuntimeError,lambda:history.execute(guarded))
    def macro(*actions):
        def perform(state):
            for action in actions:state=action(state)
            return state
        return perform
    movie=ActionCommand(receiver,macro(lambda state:dict(state,power=False),lambda state:dict(state,volume=80)),"macro")
    before=deepcopy(receiver.state);history.execute(movie);c.eq("macro after",receiver.state,{"power":False,"volume":80});history.undo();c.eq("macro undo prior state",receiver.state,before)
    c.raises("macro intermediate failure",ValueError,lambda:history.execute(ActionCommand(receiver,macro(lambda state:dict(state,volume=1),fail),"bad macro")))
    c.eq("model macro failure leaves receiver",receiver.state,before)
    receiver.state["volume"]=22;c.raises("outside change detected by value",RuntimeError,history.undo)
    doc=ModelReceiver({"content":""});edits=CommandHistory(doc)
    def insert(text):return ActionCommand(doc,lambda state:{"content":state["content"]+text},"insert")
    def delete(length):
        def operation(state):
            if type(length)is not int or length<0 or length>len(state["content"]):raise ValueError("valid deletion length")
            return {"content":state["content"]if length==0 else state["content"][:-length]}
        return ActionCommand(doc,operation,"delete")
    edits.execute(insert("蓝色天空"));edits.execute(insert("网"));edits.execute(delete(0));c.eq("delete0is no-op not empty",doc.state["content"],"蓝色天空网")
    edits.execute(delete(1));c.eq("delete actual suffix",doc.state["content"],"蓝色天空");edits.undo();c.eq("undo restores deleted text",doc.state["content"],"蓝色天空网")
    c.raises("invalid deletion preserves text",ValueError,lambda:edits.execute(delete(99)));c.eq("after failed deletion",doc.state["content"],"蓝色天空网")
    from collections import deque
    queue=deque([insert(" · "),insert("mbsky.com")]);before=doc.state["content"];c.eq("enqueue no execution",before,"蓝色天空网")
    while queue:edits.execute(queue.popleft())
    c.eq("FIFO actual deferred execution",doc.state["content"],"蓝色天空网 · mbsky.com")
    c.eq("queue exhausted",len(queue),0)



def run_case(out):
    c=Checks()
    command(c,out)
    return {"chapter":'python-command',"checks":c.rows,"passed":True,"scope":"named owned all24chapter named cases only; full source coverage pending"}

if __name__ == "__main__":
    output=Path(sys.argv[1]);output.mkdir(parents=True,exist_ok=False)
    print(json.dumps(run_case(output),ensure_ascii=False,default=repr))
本例需在 Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python

入口文件:projects/patterns-lab/python-command.py

预期结果与验证条件观察提示
  • 当前固定输入命名检查符合明确实际结果及失败策略
  • 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:Python 设计模式

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202611a526.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习