System Design ( Day - 44 )

Manoj KumarManoj Kumar
2 min read

Design Patterns ( Strategy Design )

Why Design Patters
Because Someone has already encountered the common problem and come up with the solution which is already proven and that can be reusable whenever that problem occurs to improve code quality and enhance communication between dev’s, by applying these patters we can tackle the common mistakes to build maintainable and scalable systems.

Robot Example
Why Inheritance is not good: We’ll stuck in creating more abstract classes to implement different features, and also the solution to inheritance in not more inheritance.
Problems with Inheritance:
1. Code Re-use
2. To add new features lot of changes are required.
3. Breaking OCP( Open Close Principle )

Strategy Design Pattern

Definition : A family of algorithm, put them into separate classes so that they can be changed at run time.

In the above example we have 3 abstract classes which are Talkable, Walkable and Flyable if we want to integrate another model in the flyable model then we have to extend it and we can override the Fly ( ) method, we can add more features to this easily and its also scalable and it will also follow the Open close principle.
if we don’t want to inherit Projection( ) also we can create a abstract class of Projection and the we can implement where ever we want to use. that’s how we can reduce inheritance.

Real life Example
Payment methods we have different payment methods like Upi, card, bank, these are the strategies of Pay method. PayNow( ) method has different payment strategies.

Conclusion
1. Encapsulate what varies & keep it separate from what remains same.
2. Solution to inheritance is not more inheritance
3. Composition should be favoured over inheritance.
4. Code to interface not to concrete class.

0
Subscribe to my newsletter

Read articles from Manoj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manoj Kumar
Manoj Kumar