我已经开始在我的项目上申请SOLID principles分.所有这些对我来说都很清楚,除了依赖项反转,因为在Python中,在另一个类(或者我不知道)中的某个类的类型中定义变量并没有变化.所以我已经用两种形式实现了依赖倒置原理,我想知道哪一种是正确的,我怎样才能纠正它们.以下是我的代码:

d1.py:

class IFood:
    def bake(self, isTendir: bool): pass
    
class Production:
    def __init__(self):
        self.food = IFood()
    
    def produce(self):
        self.food.bake(True)
        
class Bread(IFood):
    def bake(self, isTendir:bool):
        print("Bread was baked")

d2.py:

from abc import ABC, abstractmethod
class Food(ABC):
    @abstractmethod
    def bake(self, isTendir): pass
    
class Production():
    def __init__(self):
        self.bread = Bread()
    
    def produce(self):
        self.bread.bake(True)
        
class Bread(Food):
    def bake(self, isTendir:bool):
        print("Bread was baked")

推荐答案

# define a common interface any food should have and implement
class IFood:
    def bake(self): pass
    def eat(self): pass

class Bread(IFood):
    def bake(self):
        print("Bread was baked")
    def eat(self):
        print("Bread was eaten")

class Pastry(IFood):
    def bake(self):
        print("Pastry was baked")
    def eat(self):
        print("Pastry was eaten")

class Production:
    def __init__(self, food): # food now is any concrete implementation of IFood
        self.food = food # this is also dependnecy injection, as it is a parameter not hardcoded

    def produce(self):
        self.food.bake()  # uses only the common interface

    def consume(self):
        self.food.eat()  # uses only the common interface

使用它:

ProduceBread = Production(Bread())
ProducePastry = Production(Pastry())

Python-3.x相关问答推荐

正则表达式匹配并提取括号前的单词

PANDAS中当前数据帧的匹配与更新

使用 Fetch 提交表单到 Django 视图

如何将值映射到具有上限和下限的新列

如何在 20 秒后重复使用 Pillow 在现有图像上创建新图像?

过滤阈值大小数据以使用 Pyspark 或 Python 读取

如何在python 3.10中将列表项(字符串类型)转换为模块函数

有效地缩短列表,直到第一次和最后一次出现不同于 None 的值

使用 pandas 进行多类分类的总体准确度

无法使用 Python 和 Selenium 检索 href 属性

魔术8球txt文件列表

列表中的重复数字与列表理解

有没有更好的方法来判断一个数字是否是两个数字的范围

使用 python 正则表达式匹配日期

如何注释一个以另一个函数作为参数的函数?

try 注释散列变量时,ABCMeta对象不可下标

发送Electron邮件时的 MIMEText UTF-8 编码问题

aiohttp+sqlalchemy:在回滚无效事务之前无法重新连接

plt.cm.get_cmap 中可以使用哪些名称?

用于 unicode 大写单词的 Python 正则表达式