1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
| #@author: Thomas.Darimont
import inspect
class Interface(object):
pass
class IService(Interface):
def businessOperation(self,arguments):
"""some business operation"""
pass
class IBubu(Interface):
def someAction(self,arguments):
"""xxxx"""
pass
class ServiceImpl(IService,IBubu):
def businessOperation(self,arguments):
print str(arguments)
return str(arguments).upper()
def someAction(self,arguments):
print "xxx"+str(arguments)
return str(arguments)[0]
class IInvocationHandler(Interface):
def invoke(self,proxy,target,methodName,args):
"""invoke..."""
pass
class LoggingInvocationHandler(IInvocationHandler):
def invoke(self,proxy,target,methodName,args):
print "before %s" % methodName
result = getattr(target,methodName)(args)
print "after %s" % methodName
return result
class InvokableMethod:
def __init__(self,proxy,invocationTarget,methodName):
self.methodName = methodName
self.proxy = proxy
self.invocationTarget = invocationTarget
def __call__(self,args):
#print "self=%s, args=%s" % (self,args)
#return getattr(self.invocationTarget,self.methodName)(args)
return self.proxy.invocationHandler.invoke(self.proxy,self.invocationTarget,self.methodName,args)
class Proxy(object):
def __init__(self):
pass
@staticmethod
def createProxy(invocationTarget,interfaces,invocationHandler):
#print "interfaces: %s" % interfaces
proxy = Proxy()
proxy.invocationTarget = invocationTarget
proxy.invocationHandler = invocationHandler
proxy.interfaces = interfaces
proxy.interfaceMethodMap = {}
for interface in interfaces:
#print "interfaces to implement %s->%s" % (interface,dir(interface))
for key in dir(interface):
#print "checking: %s" % key
if inspect.ismethod(getattr(interface,key)):
#print "adding: %s" % key
if not key in proxy.interfaceMethodMap:
proxy.interfaceMethodMap[interface] = {key:getattr(interface,key)}
else:
proxy.interfaceMethodMap[interface][key]=getattr(interface,key)
return proxy
def __getattr__(self, name):
for interface in self.interfaces:
if name in self.interfaceMethodMap[interface]:
#print "candidate: %s " % candidate.__name__
return InvokableMethod(self,self.invocationTarget,self.interfaceMethodMap[interface][name].__name__)
return None
print ServiceImpl().businessOperation("bubu")
serviceProxy = Proxy.createProxy(ServiceImpl(), [IService(),IBubu()],LoggingInvocationHandler())
print serviceProxy.interfaces
print serviceProxy.businessOperation("test")
print "xxxxxxxxxxxxxxxxxxxxx"
print serviceProxy.someAction("test") |
Lesezeichen