Observer + Strategy in Payment System
This program integrates Observer and Strategy patterns in payment system.
Problem Statement
Write a Java program where PaymentContext uses Strategy and notifies Observers after payment.
Source Code
| 1 | import java.util.*; |
| 2 | interface PaymentStrategy { void pay(double amount); } |
| 3 | class CreditCardPayment implements PaymentStrategy { |
| 4 | public void pay(double amount){ System.out.println("Paid "+amount+" by Credit Card"); } |
| 5 | } |
| 6 | interface Observer { void update(String msg); } |
| 7 | class ConcreteObserver implements Observer { |
| 8 | String name; |
| 9 | ConcreteObserver(String n){ name=n; } |
| 10 | public void update(String msg){ System.out.println(name+" notified: "+msg); } |
| 11 | } |
| 12 | class PaymentContext { |
| 13 | PaymentStrategy ps; List<Observer> obs=new ArrayList<>(); |
| 14 | PaymentContext(PaymentStrategy ps){ this.ps=ps; } |
| 15 | void addObserver(Observer o){ obs.add(o); } |
| 16 | void execute(double amt){ |
| 17 | ps.pay(amt); |
| 18 | for(Observer o:obs) o.update("Payment of "+amt+" done"); |
| 19 | } |
| 20 | } |
| 21 | public class ObserverStrategyPayment { |
| 22 | public static void main(String[] args) { |
| 23 | System.out.println("Eduinq Observer + Strategy Payment"); |
| 24 | PaymentContext pc=new PaymentContext(new CreditCardPayment()); |
| 25 | pc.addObserver(new ConcreteObserver("Admin")); |
| 26 | pc.addObserver(new ConcreteObserver("User")); |
| 27 | pc.execute(500); |
| 28 | } |
| 29 | } |
Program Output
Eduinq Observer + Strategy Payment Paid 500.0 by Credit Card Admin notified: Payment of 500.0 done User notified: Payment of 500.0 done
Explanation
Strategy encapsulates payment logic. - Observer notifies stakeholders after payment. - Integration demonstrates flexible and reactive enterprise systems. Conclusion: Shows Observer + Strategy integration in payment system.