对象如何在不违反依赖反转原则的情况下进行通信?

2024-05-14 14:40:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个路径规划器,它将帮助人们通过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

^{pr2}$

但是,现在我不知道如何访问PathTable._table[position]。不破坏所有的OO设计原则。在

这是令人沮丧的,因为InputManager的全部工作是访问{}。但是我不能使用组合来将InputManager放在PathTable内,因为这是一个糟糕的设计。在

实现这一目标的干净方法是什么?

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


Tags: ofthetoself路径defsteptable
1条回答
网友
1楼 · 发布于 2024-05-14 14:40:40

首先在您的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

^{pr2}$

相关问题 更多 >

    热门问题