Strategy with Calculation
This program demonstrates Strategy pattern with calculation.
Problem Statement
Write a Java program where different calculation strategies are applied.
Source Code
| 1 | interface Calculation { int compute(int a,int b); } |
| 2 | class Add implements Calculation { |
| 3 | public int compute(int a,int b){ return a+b; } |
| 4 | } |
| 5 | class Multiply implements Calculation { |
| 6 | public int compute(int a,int b){ return a*b; } |
| 7 | } |
| 8 | class Context { |
| 9 | Calculation c; |
| 10 | Context(Calculation c){ this.c=c; } |
| 11 | void perform(int a,int b){ System.out.println("Result: "+c.compute(a,b)); } |
| 12 | } |
| 13 | public class StrategyCalculation { |
| 14 | public static void main(String[] args) { |
| 15 | System.out.println("Eduinq Strategy Calculation"); |
| 16 | Context c=new Context(new Add()); |
| 17 | c.perform(5,3); |
| 18 | c=new Context(new Multiply()); |
| 19 | c.perform(5,3); |
| 20 | } |
| 21 | } |
Program Output
Eduinq Strategy Calculation Result: 8 Result: 15
Explanation
Different strategies encapsulate algorithms. - Context executes chosen strategy. - This demonstrates runtime flexibility in calculations. Conclusion: Shows Strategy pattern with calculation.