Yes, inheritance means adding or changing the behavior of a class by a sub class
the traditional way of doing inheritance is by extending a class adding new methods.
Let us take an example from Java world
没有继承的继承

超级班

extending this class to add a new behavior can be done directly and easily:
没有继承的继承

遗传

真好!

But here the inheritance is static, I need to create a new class for every new functionality.
Another way of adding functionality come from Design Patterns world, it is
the Visitor Pattern which basically “represents an operation to be performed on the elements of an object structure.” but also can be utilized to define a new operation without changing the class.
One mandatory pre-requirement for this pattern is to implement it :), the implementation is adding a behavior to the class to accept the Visitor.
没有继承的继承

游客

Visitor is an interface with single (or multiple) method(s)
没有继承的继承

访客界面

Let us implement the Sub class simulator ->
没有继承的继承

访客实施

But we had to add a new class for the new functionality! , Yes, but the good thing is that we can add the functionality dynamically to single objects of the class (the same idea applied in Decorator Pattern)
没有继承的继承

访客测试器

adding another Visitor with lambda expressions
没有继承的继承

使用Lambda

A full snippet
没有继承的继承

这不会提供传统继承的完全控制和功能,但会有所帮助:)

最后一点:在您的课程中尽可能支持访客模式:)

欢迎所有评论。

from: https://dev.to//mhddurrah/inheritance-without-extends-22hn

相关文章: