What are some alternatives to inheritance?
相关问题
- Delete Messages from a Topic in Apache Kafka
- how to define constructor for Python's new Nam
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
I think you should try delegation, delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable. and it plays a beneficial role that it doesn't force you to accept all the methods of the super class.
Some alternatives:
I realise this is not Java per se, but Scala (a language running on the Java Virtual Machine) permits mixins (known as traits in Scala).
Mixins allow you to slot some functionality alongside an existing class, rather than within the inheritance tree.
I'm assuming you're playing with Java which has some rules about inheritance.
Implementing interfaces is a common and oft used option. So, for example, if you have a data-source class that talks to a RDBMS, rather than inheriting that class and using it to implement a NoSQL datasource, the both can implement the same interface.
Rather than..
Which works but is hard to read, you could use this...
Another option would be composition. Say you have employees and customers. Your two options would be...
...or...
Since Java does not have multiple inheritance and you can implement multiple interfaces, you sometimes need to do the above to make sure your development is clean and readable.
Delegation is an alternative to inheritance.
Effective Java: Favor composition over inheritance. (This actually comes from Gang of Four, as well).
The case he makes is that inheritance can cause a lot of unseemly side effects, if the extended class was not explicitly designed to be inherited. For example, any calls to
super.someMethod()
can lead you through unexpected paths of unknown code.Instead, hold a reference to the class you would have otherwise extended, and delegate to it.
Here is a link to an interview with Erich Gamma where he talks about the concept a bit.