面向对象编程交易 [英] Object-oriented programming & transactions
问题描述
一点介绍:
类包含字段和方法(这次让我跳过属性).
字段代表类的状态.
方法描述了类的行为.
Class contains fields and methods (let me skip properties this time).
Fields represent a state of the class.
Methods describe behavior of the class.
在设计良好的类中,如果抛出异常,方法不会改变类的状态,对吗?(换句话说,无论发生什么,类的状态都不应该被破坏)
In a well-designed class, a method won't change the class's state if it throws an exception, right? (In other words, whatever happens, class's state shouldn't be corrupted)
问题:
是否有框架、设计模式、最佳实践或编程语言以事务风格调用一系列方法,以便类的状态不会改变(在异常的情况下),或者一切都成功?
Is there a framework, a design pattern, best practice or a programming language to call a sequence of methods in a transactional style, so that either class's state don't get changed (in case of exception), or everything succeeds?
例如:
// the class foo is now in the state S1
foo.MoveToState2();
// it is now (supposed to be) in the state S2
foo.MoveToFinalState();
// it is now (supposed to be) in the state, namely, S3
当然,MoveToState2()
和 MoveToFinalState()
中都可能发生异常.但是从这段代码中,我希望 foo
类处于 S1 或 S3 状态.
Surely, an exception might occur both in MoveToState2()
and MoveToFinalState()
. But from this block of code I want the class foo
to be either in the state S1 or S3.
这是一个涉及单个类的简单场景,没有if
,没有while
,没有副作用,但我希望这个想法很清楚.
This is a simple scenario with a single class involved, no if
's, no while
's, no side effects, but I hope the idea is clear.
推荐答案
看看 Memento 模式
备忘录模式是一种软件设计模式,提供将对象恢复到其先前状态(通过回滚撤消)的能力.
The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).
这篇关于面向对象编程交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!