装饰器模式
装饰器模式是设计模式手册中描述的模式。它是一种很明显的修改对象行为的方法,将其封装在一个具有类似接口的装饰对象内。
不要与Python decorator混淆,后者是动态修改函数或类的语言特性。
这是在Python中使用修饰器模式的一个例子。
""" Demonstrated decorators in a world of a 10x10 grid of values 0-255. """ import random def s32_to_u16( x ): if x < 0: sign = 0xf000 else: sign = 0 bottom = x & 0x00007fff return bottom | sign def seed_from_xy( x,y ): return s32_to_u16( x ) | (s32_to_u16( y ) << 16 ) class RandomSquare: def __init__( s, seed_modifier ): s.seed_modifier = seed_modifier def get( s, x,y ): seed = seed_from_xy( x,y ) ^ s.seed_modifier random.seed( seed ) return random.randint( 0,255 ) class DataSquare: def __init__( s, initial_value = None ): s.data = [initial_value]*10*10 def get( s, x,y ): return s.data[ (y*10)+x ] # yes: these are all 10x10 def set( s, x,y, u ): s.data[ (y*10)+x ] = u class CacheDecorator: def __init__( s, decorated ): s.decorated = decorated s.cache = DataSquare() def get( s, x,y ): if s.cache.get( x,y ) == None: s.cache.set( x,y, s.decorated.get( x,y ) ) return s.cache.get( x,y ) class MaxDecorator: def __init__( s, decorated, max ): s.decorated = decorated s.max = max def get( s, x,y ): if s.decorated.get( x,y ) > s.max: return s.max return s.decorated.get( x,y ) class MinDecorator: def __init__( s, decorated, min ): s.decorated = decorated s.min = min def get( s, x,y ): if s.decorated.get( x,y ) < s.min: return s.min return s.decorated.get( x,y ) class VisibilityDecorator: def __init__( s, decorated ): s.decorated = decorated def get( s,x,y ): return s.decorated.get( x,y ) def draw(s ): for y in range( 10 ): for x in range( 10 ): print "%3d" % s.get( x,y ), print # Now, build up a pipeline of decorators: random_square = RandomSquare( 635 ) random_cache = CacheDecorator( random_square ) max_filtered = MaxDecorator( random_cache, 200 ) min_filtered = MinDecorator( max_filtered, 100 ) final = VisibilityDecorator( min_filtered ) final.draw()
输出类似:
100 100 100 100 181 161 125 100 200 100 200 100 100 200 100 200 200 184 162 100 155 100 200 100 200 200 100 200 143 100 100 200 144 200 101 143 114 200 166 136 100 147 200 200 100 100 200 141 172 100 144 161 100 200 200 200 190 125 100 177 150 200 100 175 111 195 193 128 100 100 100 200 100 200 200 129 159 105 112 100 100 101 200 200 100 100 200 100 101 120 180 200 100 100 198 151 100 195 131 100
因此,装饰器是:
它是对象被包围的其他对象,它们共享相似的接口,装饰对象似乎要屏蔽或修改或注释被封闭的对象。
Python装饰库
这一页是装饰器代码块的中央存储库,无论是否有用。它不是一个讨论修饰符语法的页面!
参考:
https://wiki.python.org/moin/DecoratorPattern
https://wiki.python.org/moin/PythonDecoratorLibrary
https://wiki.python.org/moin/PythonDecoratorLibrary?action=AttachFile&do=view&target=memoize.py
https://wiki.python.org/moin/PythonDecoratorProposals
https://www.python.org/dev/peps/pep-0318/#syntax-alternatives
在python中创建单例模式:
https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python