博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【编程思想】【设计模式】【行为模式Behavioral】备忘录模式Memento
阅读量:5149 次
发布时间:2019-06-13

本文共 3307 字,大约阅读时间需要 11 分钟。

Python版

 

https://github.com/faif/python-patterns/blob/master/behavioral/memento.py

#!/usr/bin/env python# -*- coding: utf-8 -*-"""http://code.activestate.com/recipes/413838-memento-closure/*TL;DR80Provides the ability to restore an object to its previous state."""from copy import copyfrom copy import deepcopydef memento(obj, deep=False):    state = deepcopy(obj.__dict__) if deep else copy(obj.__dict__)    def restore():        obj.__dict__.clear()        obj.__dict__.update(state)    return restoreclass Transaction(object):    """A transaction guard.    This is, in fact, just syntactic sugar around a memento closure.    """    deep = False    states = []    def __init__(self, deep, *targets):        self.deep = deep        self.targets = targets        self.commit()    def commit(self):        self.states = [memento(target, self.deep) for target in self.targets]    def rollback(self):        for a_state in self.states:            a_state()class Transactional(object):    """Adds transactional semantics to methods. Methods decorated  with    @Transactional will rollback to entry-state upon exceptions.    """    def __init__(self, method):        self.method = method    def __get__(self, obj, T):        def transaction(*args, **kwargs):            state = memento(obj)            try:                return self.method(obj, *args, **kwargs)            except Exception as e:                state()                raise e        return transactionclass NumObj(object):    def __init__(self, value):        self.value = value    def __repr__(self):        return '<%s: %r>' % (self.__class__.__name__, self.value)    def increment(self):        self.value += 1    @Transactional    def do_stuff(self):        self.value = '1111'  # <- invalid value        self.increment()  # <- will fail and rollbackif __name__ == '__main__':    num_obj = NumObj(-1)    print(num_obj)    a_transaction = Transaction(True, num_obj)    try:        for i in range(3):            num_obj.increment()            print(num_obj)        a_transaction.commit()        print('-- committed')        for i in range(3):            num_obj.increment()            print(num_obj)        num_obj.value += 'x'  # will fail        print(num_obj)    except Exception as e:        a_transaction.rollback()        print('-- rolled back')    print(num_obj)    print('-- now doing stuff ...')    try:        num_obj.do_stuff()    except Exception as e:        print('-> doing stuff failed!')        import sys        import traceback        traceback.print_exc(file=sys.stdout)    print(num_obj)### OUTPUT #### 
#
#
#
# -- committed#
#
#
# -- rolled back#
# -- now doing stuff ...# -> doing stuff failed!# Traceback (most recent call last):# File "memento.py", line 97, in
# num_obj.do_stuff()# File "memento.py", line 52, in transaction# raise e# File "memento.py", line 49, in transaction# return self.method(obj, *args, **kwargs)# File "memento.py", line 70, in do_stuff# self.increment() # <- will fail and rollback# File "memento.py", line 65, in increment# self.value += 1# TypeError: Can't convert 'int' object to str implicitly#
Python转载版

 

转载于:https://www.cnblogs.com/demonzk/p/9035630.html

你可能感兴趣的文章
Part3_lesson4---协处理器访问指令
查看>>
Asp.Net url参数加密存在特殊符号处理方法
查看>>
css3
查看>>
强化学习(五)用时序差分法(TD)求解
查看>>
Python打卡第三周
查看>>
oracle按照in的顺序进行排序
查看>>
Inferred type 'S' for type parameter 'S' is not within its bound;
查看>>
objective里面的单例模式
查看>>
Git常用命令
查看>>
jQuery 遍历
查看>>
k8s中的api server的ca证书,可以和front proxy ca证书一样么?
查看>>
【UVa-679】小球下落——二叉树的编号
查看>>
Microsoft SQL Server sa 账户 登录错误18456
查看>>
windows:nginx配置http、https反向代理
查看>>
关于滚动更新的设计技巧
查看>>
rsync+ssh
查看>>
StackOverflow程序员推荐:每个程序员都应读的30本书
查看>>
链表 相关操作思路
查看>>
张瀚荣 如何用UE4制作3D动作游戏
查看>>
SQL ALTER TABLE 语句在项目中的使用
查看>>