Comparison
Composition over inheritancevsDelegation
Composition over inheritance
the subclass needed one method overridden and inherited four others it never wanted and cannot remove.
Preferring to build behaviour by combining objects rather than by extending a base class. Inheritance couples you to everything the parent does now and everything it will do later, and it is a decision you make once at compile time; composition is a decision you can change per instance. The argument comes up whenever a class hierarchy has grown a third level, which is usually where the abstraction that justified the first level stops being true.
Full entry →Delegation
the method body is one line that calls the same method on a field, and that is the whole class's job for that method.
Holding another object and forwarding work to it, exposing only what you choose to expose. It is what composition looks like at the method level, and it is the mechanism behind every wrapper pattern in the structural cluster. It costs boilerplate — one forwarding method per operation, which is why languages that generate delegation automatically make composition noticeably more attractive.
Full entry →