我正在重构一些代码,这些代码不太可重用并且有相当多的重复代码。该代码有两个类 A 和 B,它们扩展了抽象类 I。但是 A 和 B 的子类支持概念 X 和 Y,因此结果是具体类 AX、AY、BX、BY,其中概念 X 和 Y 复制并粘贴进入每个。
所以我知道我可以在这里使用组合来委托(delegate)对功能 X 和 Y 的支持,但这也需要构建这些对象等的代码,这就是我开始阅读有关混合的原因,所以我想知道我的代码是否是一个好的解决方案
class I(ABC):
@abstractmethod
def doSomething():
pass
class ICommon(ABC):
@abstractmethod
def doSomethingCommon():
pass
class A(I, ICommon):
# the interface(s) illustrates what mixins are supported
# class B could be similar, but not necessarily with the same interfaces
def doSomething():
self.doSomethingCommon()
...
class XCommonMixin(object):
# feature X shared possibly in A and B
# I have also split features X into much smaller concise parts,
# so the could be a few of these mixins to implement the different
# features of X
def doSomethingCommon():
return 42
class AX(XCommonMixin, A):
pass
# init can be defined to construct A and bases if any as appropriate
最佳答案
是的,这正是 mixin(或者更一般地说,类)存在的目的。类应该封装与特定概念或目的相关的所有功能(例如您的 A
和 B
,也像您的 X
和Y
)。
我相信你想得太多了。您可能知道如何使用类,而 mixin 实际上只是被赋予了一个奇特名称的类,因为它们需要多重继承才能工作。 (因为 mixins 并不总是能够独立运行的完整类;它们是可以附加到其他类的功能的集合。)类是关于关注点的分离。一关心一课。为 4 个概念 A
、B
、X
和 Y
分别实现一个类,然后将它们组合起来 (具有多重继承),如您认为合适。
我强烈建议阅读What is a mixin, and why are they useful? 。 (当前)评价最高的答案很好地解释了 mixin 正是针对这种情况而存在的。
关于python - 使用mixins来实现抽象方法可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52468080/