我正在构建一个 Path Planner,它可以帮助人们在 RPG 主机游戏中规划路径。
我想创建一个表格来显示阶段中的每个步骤。我实际上有 implemented a working version of this然而,它是看似糟糕的 OOP 设计;它违反了各种原则,我认为它甚至不是合法的 OOP。 问题很明显,Table
是一个神类。
因此,我决定在牢记正确的 OOP 原则的同时重写它。我想将 Table
分成多个类。
我的问题是我需要各种对象相互交谈。但是,我的解决方案是始终使用组合。这违反了依赖原则和单一职责原则。
这是存储玩家步数的主表:
class PathTable(object):
''' A path table. '''
def __init__(self):
# table is a list of dicts, representing rows
self._table = []
@property
def table(self):
return self._table
def addStep(self, step):
''' Adds a step to the table. '''
self._table.append(step)
def rmStep(self):
''' Removes the last step from the table. '''
try:
del self._table[-1]
except:
raise IndexError('Tried to remove item from an empty table.')
现在,我创建了一个 InputManager
负责接受和验证用户输入:
class InputManager(object):
''' Responsible for managing user input. '''
def __init__(self):
pass
def addFight(self, position):
''' Add a 'fight' at table[position]. '''
# table._table[position]['input'] = 'fight'
# Need to somehow edit a particular row in the Table.
但是,现在我不知道如何访问 PathTable._table[position]
。不破坏各种面向对象的设计原则。
令人沮丧,因为 InputManager
的全部工作就是访问 PathTable
。但是我不能使用组合将 InputManager
放在 PathTable
中,因为这是糟糕的设计。
完成此任务的简洁方法是什么?
我是初学者,我正在努力学习。
最佳答案
首先在您的 PathTable
类中添加对编辑步骤行的支持:
class PathTable(object):
def __init__(self):
self._table = []
## NB : This defeats the whole point of making `_table` private
#@property
#def table(self):
# return self._table
def add_step(self, step):
''' Adds a step to the table. '''
self._table.append(step)
def rm_step(self):
''' Removes the last step from the table. '''
return self._table.pop()
def update_step(self, position, key, value):
self._table[position][key] = value
然后将 PathTable
实例传递给您的 InputManager
:
class InputManager(object):
''' Responsible for managing user input. '''
def __init__(self, path_table):
self._path_table = path_table
def add_fight(self, position):
''' Add a 'fight' at table[position]. '''
self._path_table.update_step(position, 'input', 'fight')
关于python - 对象如何在不违反依赖倒置原则的情况下进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29493431/