For decoupling between modules,A message bus is the usual way.
mentioned in other articleslua和C++An implementation of the language's message bus
The basic principle of the message bus implementation is as follows:The communicated object publishes a topic to the message bus,This topic contains message topics and message handler functions,The message subject identifies a specific subject,A message type that the message handler uses to respond to this topic.The communication object sends a specific topic and message parameters to the message bus,The bus will find the corresponding message processing function to process the request according to the message topic and message parameters.
class PyBus (object):
def __init__(self,):
self.clear()
def clear(self):
self.subscriptions = {
}
def subscribe(self, subject, owner, func):
if owner not in self.subscriptions:
self.subscriptions[owner] = {
}
self.subscriptions[owner][subject] = func
def has_subscription(self, owner, subject):
return owner in self.subscriptions and subject in self.subscriptions[owner]
def publish(self, subject, *args, **kwargs):
for owner in self.subscriptions.keys():
if self.has_subscription(owner, subject):
self.subscriptions[owner][subject](*args, **kwargs)
class BusSingleton(PyBus):
def foo(self):
pass
bus_singleton = PyBus()
The core is maintained internallysubscriptions字典
if __name__ == "__main__":
START = 1111
class Test1(object):
def start(self):
print("start1")
class Test2(object):
def start(self):
print("start2")
test1 = Test1()
test2 = Test2()
bus_singleton.subscribe(START, test1, test1.start)
bus_singleton.subscribe(START, test2, test2.start)
bus_singleton.publish(START)