A mixin is basically a class you inherit from to absorb its code -- as opposed to a class you inherit so that your objects have a certain type. In languages with multiple inheritance, mixins can be a useful way to reuse code. In Java, the concept really doesn't apply.
Decorators are certainly useful, but they're not the same as a mixin. Decorators only apply to a specific type hierarchy -- i.e., a BufferedReader can only decorate a Reader, not a JButton or a Thread. In contrast, a mixin can be extended by pretty much any class.
The link shows you how to use delegation instead of inheritance. Delegation is where you implement a method by calling a method of some other object. Delegation is very useful in Java. Some IDEs will actually automatically delegate implementation of an interface this way, which can be a big help.
It's not really the same as mixins, though, because it's not automatic, and it's fairly brittle (i.e., if the mixin adds or removes a method, the client class has to be changed, too, which isn't necessary with true mixins.) But it's about as close as you can get in Java!
Joined: Sep 28, 2008
In that case, can I say decorators are basically delegation applied in specific type hierarchy.
Its really nice to know about delegations, decorators and mixins.
Thank you so much.
author and iconoclast
Originally posted by Himalay Majumdar: In that case, can I say decorators are basically delegation applied in specific type hierarchy.
Well, no, not really. The whole idea of a decorator is that it has the same type as the object it's decorating -- a BufferedWriter is a Writer that can decorate other Writers. Any class, regardless of type, can delegate to any other class.