Operation.class
package com.fengling.pattern.strategy;
public interface Operation {
int action(int num1, int num2);
}
Add.class
package com.fengling.pattern.strategy;
public class Add implements Operation{
@Override
public int action(int num1, int num2) {
return num1 + num2;
}
}
Substract.class
package com.fengling.pattern.strategy;
public class Substract implements Operation{
@Override
public int action(int num1, int num2) {
return num1 - num2;
}
}
Multiply.class
package com.fengling.pattern.strategy;
public class Multiply implements Operation{
@Override
public int action(int num1, int num2) {
return num1 * num2;
}
}
Context.class
package com.fengling.pattern.strategy;
public class Context {
private Operation operation;
public Context(Operation operation) {
this.operation = operation;
}
public void execute(int num1, int num2) {
System.out.println(this.operation.action(num1, num2));;
}
}
StartegyDemo.class
package com.fengling.pattern.strategy;
public class StartegyDemo {
public static void main(String[] args) {
Context context1 = new Context(new Add());
context1.execute(5, 10);
Context context2 = new Context(new Substract());
context2.execute(5, 10);
Context context3 = new Context(new Multiply());
context3.execute(5, 10);
}
}