问题描述
mixin 和继承有什么区别?
What is the difference between a mixin and inheritance?
推荐答案
mixin 通常与多重继承一起使用.所以,从这个意义上说,没有区别".
A mixin is typically used with multiple inheritance. So, in that sense, there's "no difference".
细节是mixin很少用作独立对象.
The detail is that a mixin is rarely useful as a standalone object.
例如,假设您有一个名为ColorAndDimension"的 mixin,它添加了颜色属性以及宽度和高度.
For example, say you have a mixin named "ColorAndDimension", which adds a color property and width and height.
现在,您可以将 ColorAndDimension 添加到 Shape 类、Sprite 类、Car 类等中.它们都将具有相同的接口(例如 get/setColor、get/setHeight/Width 等)
Now, you could add ColorAndDimension to a, say, Shape class, a Sprite class, a Car class, etc. And they will all have the same interface (say get/setColor, get/setHeight/Width, etc.)
因此,在一般情况下,mixin 是继承.但是你可以争辩说这是一个类在整个域中的角色的问题,即 mixin 是否是一个主要的"类.类或简单的混合.
So, in the generic case a mixin IS inheritance. But you can argue it's a matter of the role of the class in the overall domain as to whether a mixin is a "primary" class or simply a mixin.
编辑——只是为了澄清.
Edit -- just to clarify.
是的,在今天的现代行话中,可以将 mixin 视为具有关联实现的接口.它真的只是简单的、古老的、日常的多重继承,使用一个普通的、古老的、日常的类.它恰好是 MI 的一个特定应用.大多数语言不给 mixin 任何特殊状态;它只是一个旨在混合"而不是独立使用的类.
Yes, a mixin can be considered, in today's modern lingo, an Interface with an associated Implementation. It really is just plain, old, everyday multiple inheritance using a plain, old, everyday class. It just happens to be a specific application of MI. Most languages don't give a mixin any special status; it's just a class that was designed to be "mixed in", rather than used standalone.
这篇关于Mixin vs 继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!