Showing posts with label inheritance vs delegation. Show all posts
Showing posts with label inheritance vs delegation. Show all posts

Monday, August 5

Delegation Design Pattern

Delegation design pattern is used by multiple classes to work collaboratively. Java emphasizes on principal of single responsibility i.e. One class should maintain code only for one specific business responsibility For example An Customer class should be responsible only for managing customer data If it starts managing the customer Orders as well It violates the principal of single responsibility. 

So we tend to segregate our overall business logic in multiple classes . Now to work in network of classes All classes need to talk to each other . If customer has to place an order it needs help of Oder class . 

Now one way to attain the capability of using Order class features in Customer class is  inheritance . Customer class may extend Order class. But Orders is not the only class Customer class is dependent on ,there are many other features that customer require , It will ask for billing of the orders. So there would be a BillManager class. Now java supports only single inheritance So you can not extend more than one class. 

What could be the other way of achieving this . You could use multiple inheritance through interface. Implementing multiple interfaces and writing their corresponding implementation classes might help in achieving the same. But would it be possible in every case to write an interface for every class Customer class is dependent on. While writing code from scratch you might provide this implementation But most of the time people have to work on existing code and there you might not have the scope of redesigning the overall class collaboration. 

So what option is left with us which we can use quite flexibly in new and well as existing code. 

Delegation design pattern provides a way of of managing this collaboration. Delegation says One class should not do everything. Customer class should use Order class code by delegating that responsibility to Order class. Customer class will create an instance of Order class to provide required object state and then on that instance will invoke methods written in Order class. Now there is no direct dependence among classes the way it was required in case of inheritance  This is very clean and loosely coupled way of achieving collaborative functionality. So sharing responsibility to other classes is Delegation and this is one of the java programming design principal .