When we talk about inheritance, we usually separate them into interface inheritance and implementation inheritance. For single inheritance, it is easy to understand and use both implement inheritance and interface inheritance. Even so, in C ++'s book, we still mentioned that when we inherit a class, we should not only think of inherited implementations, but also inherit interfaces together.
Multi-inheritance is even more complex, and it is easy to go to the strange circle of diamond inheritance. In C #, only multi-inheritance of interfaces is implemented, and multi-inheritance is not implemented. We cannot specify two or two classes as parent classes.
Mixin in ruby is an implementation of multi-implementation inheritance, that is, the implementation part is separated in the form of modules, and the module has its unique attributes, such as being unable to be instantiated, it cannot inherit other classes or be inherited by other classes. Matsumoto has an example:
Module writestreamdef write (STR) puts strenddef reads "Conflict" endendmodule readstreamdef readputs "read data" enddef reads "conflict-read" endendclass streamdef getstreamputs "Get stream" endclass readwritestream <streaminclude writestreaminclude iterator = readwritestream. newrw. getstreamrw. readrw. write ("Haha") RW. conflict
In this example, stream, readstream, writestream, and readwritestream are commonly used in network programming. In C ++, this is often a diamond inheritance, while Ruby cleverly uses Mixin, this avoids diamond inheritance.
The running result in ruby is:
Get streamread datahahaconflict-read
Even so, you still cannot avoid the most fundamental problem: Method resolve, that is, the method that determines who uses it. In the above example, we intentionally created a conflicting method conflict. From the running result, we can see that the result of the method resolve is the conflict method of readstream. We canProgramLine 28 and line 29:
Include readstreaminclude writestream
Then run the script again and the result is as follows:
Get streamread datahahaconflict
Note the difference in the result of calling the conflict method in the last line.Mixin in Ruby determines the order of method calls based on the include sequence..