E-Commerce – Implementing ‘Buy One Get One Free’ Coupon Logic

design-patternse-commerceobject-orientedPHP

Trying to solve bogo coupon logic with proper design pattern, but having trouble identifying one.
Use case: "Buy iPad get SmartCase for free"

Suppose we have the following objects:

Product:
 - getPrice

CartItem(Product p, quantity):
 - getPrice

Cart:
 - getItems()
 - addItem(CartItem ci)

Coupon(code):
 - getCode

CouponBuyOneGetOneFree(code) extends Coupon: (not sure about inheritance here)

1) What design pattern fits here?
2) What if i needed to set up the same logic without coupon but in product settings itself?

I have implemented Decorator pattern for CartItem when discount is applied to the same CartItem by this example and it works great, but still can not achieve the result of this use case.

Somehow I need to check that Ipad and SmartCase both are in the cart and apply discount to SmartCase only. Also if I add another iPad i should get another SmartCase for free.

Best Answer

No design pattern is required beside basic subclassing. You just need a Coupon interface with a single method: calculateDiscount(cart, customer). Create an implementation of Coupon for each different kind of discount, e.g. a FreeAddonCoupon or a LoyaltyCoupon.

So a Cart has CartItems and Coupons. Add the price of the items, subtract the discount for each coupon.

Related Topic