I just want to inject some design patterns into my Java code, but I don't know which style to use -- is inheritance or interface preferred? And why?
Design patterns aren't a thing to just randomly inject into your application. They're design-time sorts of things, not parmesan cheese that you sprinkle on your code after it's already baked.
That said, Josh Bloch's seminal Effective Java strongly encourages developers to use interfaces for shared behavior rather than using inheritance. This matches my own experience.
ETA: Among other reasons, if you're implementing an interface, you can easily create a mock of that interface for use in testing without worrying about the rest of the inheritance hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With