Strategy with Discount Calculation
This program applies Strategy pattern for discount calculation.
Problem Statement
Write a Java program where different discount strategies are applied.
Source Code
| 1 | interface DiscountStrategy { double apply(double amount); } |
| 2 | class NoDiscount implements DiscountStrategy { |
| 3 | public double apply(double amount){ return amount; } |
| 4 | } |
| 5 | class PercentageDiscount implements DiscountStrategy { |
| 6 | public double apply(double amount){ return amount*0.9; } |
| 7 | } |
| 8 | class Context { |
| 9 | DiscountStrategy ds; |
| 10 | Context(DiscountStrategy ds){ this.ds=ds; } |
| 11 | void checkout(double amt){ System.out.println("Final amount: "+ds.apply(amt)); } |
| 12 | } |
| 13 | public class StrategyDiscount { |
| 14 | public static void main(String[] args) { |
| 15 | System.out.println("Eduinq Strategy Discount"); |
| 16 | Context c=new Context(new NoDiscount()); |
| 17 | c.checkout(1000); |
| 18 | c=new Context(new PercentageDiscount()); |
| 19 | c.checkout(1000); |
| 20 | } |
| 21 | } |
Program Output
Eduinq Strategy Discount Final amount: 1000.0 Final amount: 900.0
Explanation
Different strategies encapsulate discount logic. - Context executes chosen strategy. - This models flexible enterprise payment systems. Conclusion: Shows Strategy pattern with discount calculation.