新手问题 ruby 中有 Mixin 这个概念吗?

wzhang1987 · 2013年01月30日 · 最后由 chucai 回复于 2013年01月31日 · 3672 次阅读

谁能简单说说这种思考的方法?

@wzhang1987 well, 我发现 ruby 中 Mixin 和 Java 中的 interface 都是优雅美妙的东西 interface 给你一个完全空的壳子,让不同的实现者有不同的行为。 Mixin 给你一个实实在在的方法,让不同的混入者有相同的行为。

Inheritance and Mixins

Some object-oriented languages (notably C++) support multiple inheritance, where a class can have more than one immediate parent, inheriting functionality from each. Although powerful, this technique can be dangerous, as the inheritance hierarchy can become ambiguous. Other languages, such as Java, support single inheritance. Here, a class can have only one immediate parent. Although cleaner (and easier to implement), single inheritance also has drawbacks---in the real world things often inherit attributes from multiple sources (a ball is both a bouncing thing and a spherical thing, for example). Ruby offers an interesting and powerful compromise, giving you the simplicity of single inheritance and the power of multiple inheritance. A Ruby class can have only one direct parent, and so Ruby is a single-inheritance language. However, Ruby classes can include the functionality of any number of mixins (a mixin is like a partial class definition). This provides a controlled multiple-inheritance-like capability with none of the drawbacks. We'll explore mixins more beginning on page 98. So far in this chapter we've been looking at classes and their methods. Now it's time to move on to the objects, such as the instances of class Song.

这就是艺术。

#3 楼 @sevk 真理总是精炼的,总结的很好

其实 mixin 也是继承,不过是经过巧妙设计的继承

matz 在书中说,mixin 是接口一个意思 从实际的项目中来说,但我们需要分解对象或者公用一部分的代码的时候, 一般会使用 mixin

需要 登录 后方可回复, 如果你还没有账号请 注册新账号