据说循环依赖是坏的和反模式。所以我的问题是下面的代码有什么问题?它是一个循环依赖的例子吗?代码是python伪代码,但应该理解。
class Manager:
_handlers = []
def on_config(self):
# do something...
# and notify about "event"
for handler in self._handlers:
handler()
def add_change_handler(self, handler):
self._handlers.append(handler)
def get_value(self):
return some_value
class Consumer:
def __init__(self, manager):
self._manager = manager
self._manager.add_change_handler(self._on_event)
def _on_change(self):
print('Got event')
def do_something(self):
self._manager.get_value()
所以:消费者得到经理:
反对该解决方案的人的论点是,创建其他类更好,这将是:
答案 0 :(得分:-1)
Circular (or cyclic) imports in Python。这个答案将帮助您更好地了解python中的循环导入。
此代码与循环依赖无关。 您也可以将此情况视为商务人士之间的交易。
#!/bin/python
class Businessman:
_trader_list = []
def __init__(self, name, goods):
self.m_name = name
self.m_goods = goods
def on_get_goods(self):
for trader in self._trader_list:
trader.buy_some(self)
def add_change_handler(self, handler):
self._trader_list.append(handler)
def del_change_handler(self, handler):
self._trader_list.remove(handler)
def buy_some(self, from_bussinessman):
print "{0} will buy some {1}s from {2}".format(
self.m_name, from_bussinessman.m_goods, from_bussinessman.m_name)
def get_goods(self):
print("{0} gets new {1}s.".format(self.m_name, self.m_goods))
self.on_get_goods()
if __name__ == "__main__":
bob = Businessman('Bob', 'apple')
jack = Businessman('Jack', 'banana')
cream = Businessman('Cream', 'rice')
# Bob notifys Jack and Cream to buy apples when he gets some.
seller1 = bob
seller1.add_change_handler(jack)
seller1.add_change_handler(cream)
seller1.get_goods()
结果是
Bob gets new apples.
Jack will buy some apples from Bob
Cream will buy some apples from Bob