The two most common techniques for reusing functionality in object-oriented systems are :
1. Class inheritance
2. Object composition
Class Inheritance :
Class inheritance lets you define the implementation of one class in terms of another's. As the internal of the parent classes are often visible to sub classes, this reuse technique is referred as White box reuse.
Advantage :
Object composition :
Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or composing objects to get more complex functionality. Object composition is requires that the objects being composed have well defined interfaces. This style of reuse is called black box reuse, because no internal details of objects are visible.
1. Class inheritance
2. Object composition
Class Inheritance :
Class inheritance lets you define the implementation of one class in terms of another's. As the internal of the parent classes are often visible to sub classes, this reuse technique is referred as White box reuse.
Advantage :
- Class inheritance is defined statically at compile time and is straightforward to use.
Disadvantage :
- You can not change the implementations inherited from parent classes at run-time, because inheritance is defined at compile-time.
- Inheritance break the encapsulation because it exposes a subclass to details of it's parent's implementation.
Object composition :
Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or composing objects to get more complex functionality. Object composition is requires that the objects being composed have well defined interfaces. This style of reuse is called black box reuse, because no internal details of objects are visible.
- Object composition is defined dynamically at run-time through objects acquiring references to other objects.
- Composition requires objects to respect to each other's interfaces.
- Favoring object composition over class inheritance helps you keep each class encapsulated and focused on one task.
Conclusion : Favor object composition over class inheritance.
Reference:
1. Design Patterns, Elements of Reusable Object-Oriented Software. Author : Gang of Four ( Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides )
1. Design Patterns, Elements of Reusable Object-Oriented Software. Author : Gang of Four ( Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides )
Comments
Post a Comment