A global sales organization needs a flexible way to apply discount logic on Opportunity records. Discounts may depend on multiple factors—seasonal campaigns, customer tiers, product categories, or special promotions. The discount rules change often and should be easy to maintain and extend without modifying core logic every time.
Using the Strategy Pattern, you can encapsulate each discount calculation in a separate Apex class. This lets you dynamically select and apply the appropriate strategy at runtime, keeping your business logic modular and scalable.
public interface DiscountStrategy {
Decimal calculateDiscount(Opportunity opp);
}
public class SeasonalDiscountStrategy implements DiscountStrategy {
public Decimal calculateDiscount(Opportunity opp) {
// 10% discount during summer (June)
if(Date.today().month() == 6) return opp.Amount * 0.10;
return 0;
}
}
public class TierBasedDiscountStrategy implements DiscountStrategy {
public Decimal calculateDiscount(Opportunity opp) {
// Gold customers get 15% discount
if(opp.Account.CustomerTier__c == 'Gold') return opp.Amount * 0.15;
return 0;
}
}
public class DiscountStrategySelector {
public static DiscountStrategy selectStrategy(Opportunity opp) {
if(opp.Account.CustomerTier__c == 'Gold')
return new TierBasedDiscountStrategy();
else if(Date.today().month() == 6)
return new SeasonalDiscountStrategy();
else
return new NoDiscountStrategy();
}
}
trigger OpportunityDiscountTrigger on Opportunity (before insert, before update) {
for(Opportunity opp : Trigger.new) {
DiscountStrategy strategy = DiscountStrategySelector.selectStrategy(opp);
opp.Discount__c = strategy.calculateDiscount(opp);
}
}
- Easy Extension: Add new discount rules by simply creating new strategy classes.
- Clean Separation: Business logic is decoupled, modular, and easy to test.
- Maintainability: Changes require minimal updates—no need to touch the trigger or selector for new rules.
- Scalability: Supports complex discount scenarios as business grows.
This pattern is ideal for any scenario where business logic can vary based on dynamic conditions—such as approval processes, validation rules, or pricing engines.
Want to see more Apex patterns in action? Let us know in the comments!
Post a Comment