In this below code basically three 3 main classes
- 1 classes that implements Operation interface
- 2 Classes that extents from Context class
- 3 Main class that demonstrate Strategy pattern
So my question is that how is this a strategy pattern apply in this code
Operation interface
public interface Operation {
public float run(float a,float b);
}
Add class
public class Add implements Operation{
@Override
public float run(float a, float b) {
return a+b;
}
}
Multiply class
public class Multiply implements Operation {
@Override
public float run(float a, float b) {
return a*b;
}
}
Subtract class
public class Subtract implements Operation {
@Override
public float run(float a, float b) {
return a-b;
}
}
Context class
public abstract class Context {
protected Operation OP;
public abstract float run(float a,float b);
}
AddContext class
public class AddContext extends Context {
public AddContext(){
OP = new Add();
}
@Override
public float run(float a, float b) {
return OP.run(a,b);
}
}
MultiplyContext class
public class MultiplyContext extends Context {
public MultiplyContext(){
OP = new Multiply();
}
@Override
public float run(float a, float b) {
return OP.run(a,b);
}
}
SubtractContest class
public class SubtractContext extends Context {
public SubtractContext(){
OP = new Subtract();
}
@Override
public float run(float a, float b) {
return OP.run(a,b);
}
}
Main class
public class Main {
public static void main(String... o){
// 1st Strategy
Context c = new AddContext();
System.out.println(c.run(1,2));
// 2nd Strategy
c = new SubtractContext();
System.out.println(c.run(1,2));
// 3rd Strategy
c = new MultiplyContext();
System.out.println(c.run(1,2));
}
}
Aucun commentaire:
Enregistrer un commentaire