I’m sharing my experience with a task assigned to me one year ago. It was a new feature in our system and I was responsible to finish it bug-free and in a short time.
The product owner had asked me to create a page to generate discount coupons (random string coupon, fixed string coupon). When I started analyzing the requirements, I guessed in the future, they may ask for generating the coupons in a different way such as the generation of just numeric coupons.
I’m going to share my code with you but before getting started, I would like to share the class diagram of the Strategy pattern with you.
I created an interface as mentioned in the class diagram. This interface will be implemented in strategy classes.
Now it’s time for creating classes that are responsible for generating discount coupons.
- Random Coupon Generator
- Exact Coupon Generator
As you see, I created two simple classes implementing our ‘GenerateCouponStrategy’ interface and wrote a logic inside Generate() method to make a discount coupon.
isProcessable() method will be called from context class to prevent executing the wrong strategy for the generation of the discount coupons.
It’s time to create our Context class as mentioned in the diagram.
This class has two methods of setStrategy() and generateCoupon().
- setStrategy() method is used to set our strategies inside the context class, it’s like a container that stores our strategies.
- generateCoupon() method is used for generating the coupons!
Ok, we are almost done! let’s check out the latest part:
I’ve tried to keep it simple, you can add a new parameter to generate() method pass numbers of required discount coupons and create multiple discounts in one call.
I pushed this example on my Github you can check the source code there.