Strategy in Payment Processing
This program applies Strategy pattern in payment systems.
Problem Statement
Write a Java program where different payment strategies are applied at runtime.
Source Code
| 1 | interface PaymentStrategy { void pay(double amount); } |
| 2 | class CreditCardPayment implements PaymentStrategy { |
| 3 | public void pay(double amount){ System.out.println("Paid "+amount+" by Credit Card"); } |
| 4 | } |
| 5 | class PayPalPayment implements PaymentStrategy { |
| 6 | public void pay(double amount){ System.out.println("Paid "+amount+" by PayPal"); } |
| 7 | } |
| 8 | class PaymentContext { |
| 9 | PaymentStrategy ps; |
| 10 | PaymentContext(PaymentStrategy ps){ this.ps=ps; } |
| 11 | void execute(double amt){ ps.pay(amt); } |
| 12 | } |
| 13 | public class StrategyPayment { |
| 14 | public static void main(String[] args) { |
| 15 | System.out.println("Eduinq Strategy Payment"); |
| 16 | PaymentContext pc=new PaymentContext(new CreditCardPayment()); |
| 17 | pc.execute(500); |
| 18 | pc=new PaymentContext(new PayPalPayment()); |
| 19 | pc.execute(700); |
| 20 | } |
| 21 | } |
Program Output
Eduinq Strategy Payment Paid 500.0 by Credit Card Paid 700.0 by PayPal
Explanation
Strategy encapsulates payment algorithms. - Context executes chosen strategy. - This models flexible enterprise payment systems. Conclusion: Shows Strategy pattern in payment systems.