Strategy Pattern with Polymorphism
This program integrates Strategy pattern with polymorphism.
Problem Statement
Write a Java program where different strategies implement Payment interface.
Source Code
| 1 | interface Payment { void pay(); } |
| 2 | class CreditCardPayment implements Payment { public void pay(){ System.out.println("Eduinq Paid via Credit Card"); } } |
| 3 | class PayPalPayment implements Payment { public void pay(){ System.out.println("Eduinq Paid via PayPal"); } } |
| 4 | public class StrategyPolymorphism { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq Strategy Polymorphism"); |
| 7 | Payment p1=new CreditCardPayment(); |
| 8 | Payment p2=new PayPalPayment(); |
| 9 | p1.pay(); p2.pay(); |
| 10 | } |
| 11 | } |
Program Output
Eduinq Strategy Polymorphism Eduinq Paid via Credit Card Eduinq Paid via PayPal
Explanation
Strategy pattern defines a family of algorithms encapsulated in interfaces. - Polymorphism allows switching between different strategies at runtime. - This integration demonstrates flexible design where behavior can be changed dynamically without altering client code. - Widely used in payment systems, authentication, and sorting algorithms. Conclusion: Shows Strategy pattern with polymorphism.