|
1 | | -#coding: utf8 |
2 | | - |
3 | | -import time |
4 | | - |
5 | | -""" |
6 | | -python在语言层面就支持装饰器模式, |
7 | | -下面用一个绕口的方式,说明python中的装饰器: |
8 | | - 装饰器是一个可调用对象 |
9 | | - 装饰器需要返回一个可调用对象 |
10 | | - 装饰器用来装饰可调用对象 |
11 | | -python中的可调用对象包括: |
12 | | - 函数 |
13 | | - 方法 |
14 | | - 实现了__call__方法的对象 |
15 | | - 类 |
16 | | -装饰器分为两类: |
17 | | - 不带参数的装饰器 |
18 | | - 带参数的装饰器 |
19 | | -
|
20 | | -@decorator |
21 | | -def func(): |
22 | | - pass |
23 | | -等同于 func = decorator(func) |
24 | | -
|
25 | | -@decorator2 |
26 | | -@decorator1 |
27 | | -def func(): |
28 | | - pass |
29 | | -等同于 func = decorator2(decorator1(func)) |
30 | | -
|
31 | | -@decorator(arg) |
32 | | -def func(): |
33 | | - pass |
34 | | -等同于 func = decorator(arg)(func) |
35 | | -""" |
36 | | - |
37 | | -class LogDecorator: |
38 | | - def __init__(self, wrapped_callable_object): |
39 | | - self._callable = wrapped_callable_object |
40 | | - |
41 | | - def __call__(self, *a, **kw): |
42 | | - print("begin to invoked %s with %s, %s" % (self._callable, a, kw)) |
43 | | - result = self._callable(*a, **kw) |
44 | | - print("invoked succesfully") |
45 | | - return result |
46 | | - |
47 | | -def execution_time_decorator(func): |
48 | | - def _inner(*a, **kw): |
49 | | - start_time = time.time() |
50 | | - result = func(*a, **kw) |
51 | | - print("%s executed in %s s" % (func, time.time()-start_time)) |
52 | | - return result |
53 | | - return _inner |
| 1 | +# coding: utf8 |
| 2 | + |
| 3 | +import abc |
| 4 | + |
| 5 | + |
| 6 | +class Component(object): |
| 7 | + __metaclass__ = abc.ABCMeta |
| 8 | + |
| 9 | + @abc.abstractmethod |
| 10 | + def process(self): |
| 11 | + pass |
| 12 | + |
| 13 | + |
| 14 | +class ConcreteComponent(Component): |
| 15 | + def process(self): |
| 16 | + print("process in ConcreteComponent") |
| 17 | + |
| 18 | + |
| 19 | +class Decorator(Component): |
| 20 | + def __init__(self, component): |
| 21 | + self._component = component |
| 22 | + |
| 23 | + def process(self): |
| 24 | + self.before() |
| 25 | + self._component.process() |
| 26 | + self.after() |
| 27 | + |
| 28 | + @abc.abstractmethod |
| 29 | + def before(self): |
| 30 | + pass |
| 31 | + |
| 32 | + @abc.abstractmethod |
| 33 | + def after(self): |
| 34 | + pass |
| 35 | + |
| 36 | + |
| 37 | +class LogDecorator(Decorator): |
| 38 | + def before(self): |
| 39 | + print("before calling process") |
| 40 | + |
| 41 | + def after(self): |
| 42 | + print("after calling process") |
| 43 | + |
54 | 44 |
|
55 | 45 | if __name__ == "__main__": |
56 | | - @LogDecorator |
57 | | - @execution_time_decorator |
58 | | - def func1(): |
59 | | - time.sleep(1) |
| 46 | + import unittest |
| 47 | + |
60 | 48 |
|
61 | | - func1() |
| 49 | + class DecoratorTest(unittest.TestCase): |
| 50 | + def testDecorator(self): |
| 51 | + component = ConcreteComponent() |
| 52 | + decorator = LogDecorator(component) |
| 53 | + decorator.process() |
62 | 54 |
|
| 55 | + unittest.main() |
0 commit comments