
Undo/Redo是CAx软件中常见的操作功能,其实现方法也相对比较成熟,本文对FreeCAD Transaction机制进行深入分析,一方面是为了深化对FreeCAD代码的理解,学习其设计思路,领略其设计模式的使用范式;另一方面则考虑到Undo/Redo功能的普遍性,旨在概述Undo/Redo的实现原理,希望对从事国产CAx软件开发的朋友有所帮助。注1:限于笔者研究水平,难免有理解不当,欢迎批评指正。注2:文章内容会不定期更新,欢迎交流讨论。零、关于Redo/Undo的逻辑分析0.1 CommandCommand可以理解为用户通过界面向软件业务层发起的一次请求。一个Command可能修改一个对象,也可能修改多个对象。要求Command支持Undo/Redo,也即要求command具有可逆性,即通过command对应的逆操作使系统状态恢复到该命令执行之前的状态。0.2 TransactionRef. fromWhat is a Transaction?A transaction is a group of operations that have the following properties: atomic, consistent, isolated, and durable (ACID). The support of transactions enables new types of applications to be developed, while simplifying the development process and making the application more robust.Atomicity: A transaction is an atomic unit of work; either all operations are completed successfully, or none are applied.Consistency: Transactions transform the database from one consistent state to another, ensuring that data remains valid according to defined rules.Isolation: Transactions operate independently of one another, meaning the intermediate state of a transaction is not visible to other transactions.Durability: Once a transaction is committed, its effects are permanent, even in the event of a system failure.0.3 CRUD进一步分析,对于单个对象的操作无非就是增(Create)、查(Read)、改(Update)、删(Delete)等类操作,而查询操作通常并不会改变对象的状态,如此,变可将Transaction进一步分解为增(Create)、改(Update)、删(Delete)组成的有序序列。0.4 Mutation Operation一、预修知识1.1 设计模式Undo/Redo经典实现是采用Command、Memento等设计模式。GoF、Alexander Shvets等已经就Command、Memento等相关设计模式进行了经典阐述,这里不再赘述,仅简要罗列其技术要点。Command模式将请求封装成了对象,提供了命令响应的统一接口。Commandis a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method