When to consider the use of the strategy design pattern?
The strategy pattern is a good solution for those cases in which we need the program to select which code alternative, of several similar code alternatives, to implement at runtime (i.e. when the program is running).
The strategy pattern is a good solution for those cases in which we need the program to select which code alternative to implement at runtime.
We all know what code alternatives are. Consider the following plain function with the name of couponGenerator that generates different coupons for different car types. To those who are interested in buying a BMW, it offers a different coupon than to those who are interested in buying a Mercedes.
// Generate different coupons for different car types.
function cupounGenerator($car)
{
if($car == "bmw")
{
$cupoun = "Get 5% off the price of your new BMW";
}
else if($car == "mercedes")
{
$cupoun = "Get 7% off the price of your new Mercedes";
}
return $cupoun;
}
The coupon is the discount rate that is offered to the customers interested in purchasing a car. It can take a number of factors into account for weighting the discount rate. For example, we can weigh into the decision of the discount rate the following factors:
- We might want to offer a discount during a downturn in the purchase of cars.
- We might want to offer a discount when the stock of cars for sale is too large.
Let's rewrite the function couponGenerator to take into account these factors. For this purpose, we add the following variables:
- $isHighSeason to indicate if it is a period of record sales.
- $bigStock to indicate if there are a large number of cars in stock.
The rewritten code now includes the new variables that affect the discount rate:
// Add to the discount during the downturn or if the stock of cars is too large.
function cupounGenerator($car)
{
$discount = 0;
$isHighSeason = false;
$bigStock = true;
if($car == "bmw")
{
if(!$isHighSeason) {$discount += 5;}
if($bigStock) {$discount += 7;}
}
else if($car == "mercedes")
{
if(!$isHighSeason) {$discount += 4;}
if($bigStock) {$discount += 10;}
}
return $cupoun = "Get {$discount}% off the price of your new car.";
}
echo cupounGenerator("bmw");
Result:
Get 12% off the price of your new car