Python,循环依赖关系和单身人士 [英] Python, Circular Dependencies, and Singletons
问题描述
我在这里挖了一个洞。
我正在PyDev中使用Python / Kivy应用程序。
I'm working on a Python/Kivy app in PyDev.
应用程序运行在许多系统(大约10个)上,因此我将它们推入引擎来处理所有内容。
The app runs off of many systems (about 10), so I shoved them into an engine to handle everything.
为了便于访问,我通过(最差的)单身人士获取引擎
For ease of access, I grab the engine via (the worst) singletons
main.py
#main.py
from code import engine
class MyApp(App):
def build(self):
engine.GetInstance().Initialize()
if __name__ == '__main__':
MyApp().run()
engine.py
engine.py
#engine.py
from code import system1
from code import system2
gEngineInstance = None
def GetInstance():
global gEngineInstance
if (gEngineInstance == None):
gEngineInstance = Engine()
return gEngineInstance
class Engine():
mSystem1 = None
mSystem2 = None
def Initialize(self):
self.mSystem1 = system1.System1()
self.mSystem2 = system2.System2()
# Omitted
Unfortunatley,这导致了一些讨厌的循环依赖。
Unfortunatley, this resulted in some nasty circular dependencies.
Main必须创建引擎,并且知道关于它,它运行引擎导入,运行系统导入。
问题:系统导入然后导入引擎,循环引用。
Main has to create engine, and know about it, which runs engines imports, which runs the system imports. Problem: Systems imports then import engine, circular reference.
system1.py
system1.py
#system1.py
from code import engine
class System1():
def SomeMethod(self):
engine.GetInstance().mSystem2.DoThings()
你得到了图片。
我现在用这个可怕的代码绕过了这个:
You get the picture. I bypassed this for now with this hideous code all over the place:
system1.py
system1.py
#system1.py
class System1():
def SomeMethod(self):
from code import engine
engine.GetInstance().mSystem2.DoThings()
这会阻止导入发生直到该行,很好,但它看起来不对,感觉就像我做错了。
This stops the import from happening until that line, which is fine, but it looks wrong, eveyrthing feels like i'm doing things wrong.
我很想把Engine作为对每个系统构造函数的引用传递,但是这有点重构,我想知道是否有更好的方法来解决未来的这种单例/循环引用问题。
I'm tempted to just pass Engine as a reference to every systems constructor, but thats a bit of refactoring, and i'd like to know if there's a more decent way to fix this sort of singleton/circular reference issue for the future.
推荐答案
如何使用注册机制,其中每个系统
模块注册自己的引擎
使用一些模块级代码的类:
How about having a "registration" mechanism, where each system
module "registers" itself with the Engine
class using some module-level code:
engine.py
class Engine():
@classmethod
def register(cls, type):
...
system1.py
from engine import Engine
class System1():
...
Engine.register(System1)
这样,引擎
并不直接知道插入的内容。
That way, the Engine
doesn't directly have to know what gets plugged into it.
这篇关于Python,循环依赖关系和单身人士的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!