How Strategy Pattern help in reducing code duplication, avoid type casting and make design Better

Yesterday I was trying to refactor some code which has lots of code duplication, static type casting between sub types and cohesive. After some refactoring I decided to use java’s strategy design pattern to remove code duplication and make it extendable.

The motive behind using strategy pattern was to move behavior out of the class, make it maximize cohesion and minimize coupling and use of interface, abstract class to avoid tide coupling.

So let’s discuss this with an example…

You have an Ad agency which has a service which rotate different types of ad in some different ways. So I move out the behavior of rotating ad into one interface.

Now, since we have different types of ads so it a good design to create one abstract ad class with some basic functionality…

Here you can see I have created one abstract getType() method which return the sub-class type. This way we don’t need to type case classes in rotate() method…

Now create our Ad class which extends Ad and implements given abstract methods…

Take a look on rotate() method, which takes BannedAd as a parameter and avoid Type-casting.

Create one class which has the Ad rotate behavior which we decouple from our main BannerAd class. This way I have moved the behavior of rotating ad and make it minimum coupling.

Now it time to test our Ad Service…

Screenshot of JUnit..

About the Author

has written 69 posts.

I Love Coding, Analyzing, Designing and doing it the right way. I am obsessed about learn anything new daily and sharing what I have learn each Day. This Blog is journey of my Zeal, going through step by step to the mountain of desire to become prefect. Google Wanna Hire me ?

Copyright © 2020 All rights reserved.
Proudly powered by WordPress. Developed by 7Tech Solutions