如果需要实例化具有默认值的依赖项以便稍后更新它们,那么应用依赖项反转是否有意义?

问题描述 投票:0回答:1

在此示例中,数据库获取返回图像的 get_image 方法。为了遵守 DIP,示例包含所有必要的接口。


import abc


class ImageInterface(abc.ABC):
    """Represent and manipulate images"""


class ImageParserInterface(abc.ABC):
    """Image parser"""

    @abc.abstractmethod
    def decode(self, data: str) -> ImageInterface:
        """Parse string to Image"""


class DatabaseInterface(abc.ABC):
    """Communicate with a database"""

    @abc.abstractmethod
    def get_image(self, image_id: str) -> ImageInterface:
        """Get an image stored in the database from it's id"""


class ImageRGB(ImageInterface):
    """Represent and manipulate RGB images"""


class ImageParserMongoDBToRGB(ImageParserInterface):
    """Convert result from MongoDB query to ImageRGB"""

    def decode(self, data: str) -> ImageInterface:
        """Parse string to Image"""
        return ImageRGB()


class DatabaseMongoDB(DatabaseInterface):
    """Communicate with a MongoDB database"""

    def __init__(self, image_parser: ImageParserInterface):
        self._image_parser = image_parser

    @abc.abstractmethod
    def fetch_image_data(self, image_id: str) -> str:
        ...

    def get_image(self, image_id: str) -> ImageInterface:
        image_data = self.fetch_image_data(image_id)
        return self._image_parser.decode(image_data)
   

依赖倒置原则指出

  • A1:高级模块不应从低级模块导入任何内容
  • A2:两者都应该依赖于抽象(例如接口)。
  • B1:抽象不应该依赖于细节。
  • B2:细节(具体实现)应该取决于抽象。

A1 和 B1 受到尊重,因为所有接口仅依赖于接口。
A2 和 B2 不是,因为 ImageParserMongoDBToRGB 依赖于 ImageRGB,而 ImageRGB 不是一个接口。

在这种情况下,使用空 ImageRGB 初始化 ImageParserMongoDBToRGB 是否有意义,如下所示,只是为了遵守依赖倒置原则?

class ImageParserMongoDBToRGB(ImageParserInterface):
    """Convert result from MongoDB query to ImageRGB"""

   def __init__(self, image: ImageInterface):
      self.image = image

    def decode(self, data: str) -> ImageInterface:
        """Parse string to Image"""
        self.image.data = image_data
        return self.image
oop design-patterns solid-principles dependency-inversion
1个回答
0
投票

我的猜测是您将依赖关系与数据混淆了。 您的案例中的一个依赖项是您的 MongoDB 持久层。实际上,由于您正在以特定格式序列化图像,并与 MongoDB 绑定在一起,因此您的

DatabaseMongoDB
类应该负责加载数据并将其映射到实现
ImageInterface
的类。

© www.soinside.com 2019 - 2024. All rights reserved.