MOHAMD DORRA Posted on May 26, 2019 Inheritance without extends #java #inheritance #patterns #visitor 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 Super class extending this class to add a new behavior can be done directly and easily: Inherited nice ! 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 Visitor is an interface with single (or multiple) method(s) Visitor Interface Let us implement the Sub class simulator -> Visitor Implementation 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) Visitor Tester adding another Visitor with lambda expressions Using Lambda A full snippet This will not give a full control and capabilities of traditional inheritance but it helps :) As a final note: try to support visitor pattern whenever possible in your classes :) all comments are welcomed. Top comments (0) Subscribe Personal Trusted User Create template Templates let you quickly answer FAQs or store snippets for re-use. Submit Preview Dismiss Code of Conduct • Report abuse Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)