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

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

Posted on

java strategy design pattern - How Strategy Pattern help in reducing code duplication, avoid type casting and make design BetterYesterday I used to be making an attempt to refactor some code which has a number of code duplication, static kind casting between sub varieties and cohesive. After some refactoring I made a decision to make use of java’s technique design sample to take away code duplication and make it extendable.

The motive behind utilizing technique sample was to maneuver conduct out of the category, make it maximize cohesion and reduce coupling and use of interface, summary class to keep away from tide coupling.

So let’s talk about this with an instance…

You might have an Advert company which has a service which rotate various kinds of advert in some other ways. So I transfer out the conduct of rotating advert into one interface.

Now, since we now have various kinds of adverts so it an excellent design to create one summary advert class with some fundamental performance…

Right here you possibly can see I’ve created one summary getType() technique which return the sub-class kind. This manner we don’t have to kind case courses in rotate() technique…

Now create our Advert class which extends Advert and implements given summary strategies…

Have a look on rotate() technique, which takes BannedAd as a parameter and keep away from Sort-casting.

Create one class which has the Advert rotate conduct which we decouple from our major BannerAd class. This manner I’ve moved the conduct of rotating advert and make it minimal coupling.

Now it time to check our Advert Service…

Screenshot of JUnit..

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

Supply techzoo.org