python一种分派消息的方法
时间:2009-06-19 来源:nahuat
#!/usr/bin/python
# -*- coding: utf8 -*-
class dispatch:
def __init__(self):
self.__map = dict()
def attach(self, instance):
id, map = instance.callback_traits
self.__map[id] = map
def detach(self, instance):
del self.__map[instance.callback_traits[0]]
def execute(self, instance, method, request):
if self.__map.has_key(instance):
method_map = self.__map[instance]
if method_map.has_key(method):
method_map[method].__call__(request)
class role:
def __init__(self):
self.callback_traits = (1, {1:self.login, 2:self.move})
def login(self, request):
print 'role::login', request
def move(self, request):
print 'role::move', request
class package:
def __init__(self, name):
self.callback_traits = (2, {1:self.add, 2:self.remove})
self.name = name
def add(self, request):
print 'package::add(%s)' % self.name, request
def remove(self, request):
print 'package::remove(%s)' % self.name, request
if __name__ == '__main__':
d = dispatch()
p1, p2 = package('one'), package('two')
p = p2
d.attach(role())
d.attach(p)
d.execute(1, 1, 'hello')
d.execute(1, 2, 'world')
d.execute(2, 1, 'foo bar')
d.execute(2, 2, 'hello, world!')
d.detach(p)
d.execute(2, 1, '(del)foo bar')
d.execute(2, 2, '(del)hello, world!')
# -*- coding: utf8 -*-
class dispatch:
def __init__(self):
self.__map = dict()
def attach(self, instance):
id, map = instance.callback_traits
self.__map[id] = map
def detach(self, instance):
del self.__map[instance.callback_traits[0]]
def execute(self, instance, method, request):
if self.__map.has_key(instance):
method_map = self.__map[instance]
if method_map.has_key(method):
method_map[method].__call__(request)
class role:
def __init__(self):
self.callback_traits = (1, {1:self.login, 2:self.move})
def login(self, request):
print 'role::login', request
def move(self, request):
print 'role::move', request
class package:
def __init__(self, name):
self.callback_traits = (2, {1:self.add, 2:self.remove})
self.name = name
def add(self, request):
print 'package::add(%s)' % self.name, request
def remove(self, request):
print 'package::remove(%s)' % self.name, request
if __name__ == '__main__':
d = dispatch()
p1, p2 = package('one'), package('two')
p = p2
d.attach(role())
d.attach(p)
d.execute(1, 1, 'hello')
d.execute(1, 2, 'world')
d.execute(2, 1, 'foo bar')
d.execute(2, 2, 'hello, world!')
d.detach(p)
d.execute(2, 1, '(del)foo bar')
d.execute(2, 2, '(del)hello, world!')
相关阅读 更多 +