抽象类和 Mixin 有什么区别?
I just found an article on a framework in Java that apparently allows it to support Mixins and something called Composite Oriented Programming (which for all I know might even be the same thing...) I've also heard of/worked with AOP, and I'm not sure how it differs from this either...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在与语言无关的层面上,mixin 只是向类添加功能,更多的是为了程序员的方便并避免代码重复。 抽象(基)类形成 is-a 关系并允许多态性。 过度使用继承的一个原因是,它是一种实现 mixin 的简单方法,而无需使用并不真正支持它们的语言编写任何样板文件。 问题在于,您将多态 is-a 关系声明为副作用,使您的 API 更加混乱,并可能增加歧义。 因此,D 和 Ruby 等较新的语言支持 mixins 作为本机功能,从而可以方便地向类添加一堆功能,而无需声明多态 is-a 关系。
At a language-agnostic level, a mixin just adds functionality to a class, and is more for programmer convenience and to avoid code duplication. An abstract (base) class forms an is-a relationship and allows for polymorphism. One reason why inheritance is overused is that it's an easy way to implement mixins without writing any boilerplate in languages that don't really support them. The problem is that you're declaring a polymorphic is-a relationship as a side effect, making your API more confusing and possibly adding ambiguity. Hence, newer languages like D and Ruby support mixins as native features, allowing a convenient way to add a bunch of functionality to a class without declaring a polymorphic is-a relationship.