2

我正在构建一个路径规划器,它将帮助人们通过 RPG 控制台游戏规划路径。

我想创建一个表格来显示整个阶段的每个步骤。我实际上已经实现了这个的工作版本,但是,它似乎是糟糕的 OOP 设计;它违反了各种原则,我认为它甚至不是合法的 OOP。问题是,很明显,那Table是神级。

因此,我决定重写它,同时尝试牢记正确的 OOP 原则。我想Table分成多个班级。

我的问题是我需要各种对象相互交谈。但是,我的解决方案是始终使用composition。这打破了依赖原则以及单一责任原则。

这是存储玩家步数的主表:

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]. 在不打破各种OO设计原则的情况下。

这很令人沮丧,因为整个工作InputManager就是访问PathTable. 但是我不能用构图放在InputManager里面PathTable,因为它是糟糕的设计。

什么是完成此任务的干净方法?

我是初学者,我正在努力学习。

4

1 回答 1

1

首先添加对编辑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')
于 2015-04-07T16:05:20.813 回答