Python 具有多个依赖组件的系统模式中的循环依赖
需要以下模式:Python 具有多个依赖组件的系统模式中的循环依赖,python,design-patterns,circular-dependency,Python,Design Patterns,Circular Dependency,需要以下模式: 计算机有物理组件(硬盘、屏幕、扬声器) 您可以在其上安装应用程序(这是计算机对应用程序的所有了解) 没有计算机,应用程序无法运行,必须安装 应用程序可以使用计算机的物理组件 由于计算机包含应用程序,且应用程序需要访问计算机,因此存在循环依赖关系。这是一个适当的情况下使用它,还是有一个更好的模式,这样的问题 示例代码: class Screen: def display(self, image): print('Displaying "{}"'.forma
class Screen:
def display(self, image):
print('Displaying "{}"'.format(image))
class Speaker:
def play(self, sound):
print('Playing "{}"'.format(sound))
class HardDrive:
def write(self, data):
print('Writing "{}" to disk'.format(data))
class Applications(dict):
def __setitem__(self, name, app):
try:
self.__getitem__(name)
raise PermissionError('App "{name}" is already installed!'.format(name=name))
except KeyError:
super(Applications, self).__setitem__(name, app)
class Computer:
def __init__(self):
self.screen = Screen()
self.speaker = Speaker()
self.disk = HardDrive()
self.apps = Applications()
def install_app(self, factory, *args, **kwargs):
app = factory(self, *args, **kwargs)
self.apps[app.name] = app
def __getattr__(self, item):
try:
return self.apps[item]
except KeyError:
pass
class App(object):
def __init__(self, computer, name=None):
self.computer = computer
self.name = name
class PdfReader(App):
def __init__(self, computer, name='pdf_reader'):
super(PdfReader, self).__init__(computer, name)
self.computer.disk.write('pdf reader data')
def read_document(self, document):
self.computer.screen.display(document)
class VideoPlayer(App):
def __init__(self, computer, name='video_player'):
super(VideoPlayer, self).__init__(computer, name)
self.computer.disk.write('pdf reader data')
def play_video(self, video):
self.computer.screen.display(video)
self.computer.speaker.play(video)
if __name__ == '__main__':
home_pc = Computer()
home_pc.install_app(PdfReader)
home_pc.install_app(VideoPlayer)
home_pc.pdf_reader.read_document('Harry_Potter.pdf')
home_pc.video_player.play_video('Pulp_Fiction.mp4')
为什么是圆形的?为什么(缺少)安装程序
class Computer:
# no change: def __init__(self):
def install_app(self, installer, *args, **kwargs):
try:
app = installer(self, *args, **kwargs) # def installer() missing
self.apps[app.name] = app # install if it worked # but I assume it does smth
except InstallError ex:
# do something if installer throws InstallError
pass
如果安装过程不起作用,则引发InstallError。如果有效,只需将应用程序添加到计算机。不涉及循环
顺便说一句,我的笔记本电脑上有大约2-4个视频播放器软件(Real player、vlc等)-如果你允许在实例化应用程序时提供应用程序的“名称”,以允许使用多个视频播放器应用程序,你会变得更灵活。1。循环,因为应用程序具有
computer
属性。电脑里也有应用程序。2.在这种情况下,installer
是类对象。所以installer()
正在调用\uuuu init\uuuu
。也许这个名字有点误导,改名为工厂
。3.视频播放器应该是一个具体的应用。VLCPlayer将成为一个子类。但从技术上讲,应该可以安装同一应用程序的多个实例,因此将name
作为实例变量是有意义的。