Composition vs Inheritance in MVP

后端 未结 5 1305
挽巷
挽巷 2020-12-29 05:43

I\'m using MVP pattern to develop a large scale application. While working in the development I have come up with the question whether if composition or inheritance should b

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 06:36

    Of course, when Foo does not extends Bar, you need to add more code, because you have extra getters and setters. But the very big benefit is that Foo does not depends on Bar anymore. This may look a very minor benefit, but imagine what it would look like if you use inhenritance with more than 50 classes... it would be hell, without any logic, and it would be very complicated if you had to change a component used in a class that is extended by several other classes.

    For maintenace reason, avoid using inheritance. As you said, "a Bar is not a Foo", so Bar should not extend Foo. For what I have experienced, inheritance is never a good solution, and should be used only for a family of classes (when using a composite pattern for example).

提交回复
热议问题