场景引入
个人感觉就和java中的多态性是差不多原理的,即:先定义一个接口,其中定义了一个抽象方法,比如两个数组的计算操作。然后用一些实现类去实现这个接口,实现其中具体的计算操作,比如有:加、减、乘、除。然后在使用时,我们只需要指定是哪一个具体的实现策略即可。
结构图
代码
策略
public interface strategy<T> {
int operate(int o1
,int o2
);
}
策略实现
public class Add implements strategy{
@Override
public int operate(int o1
, int o2
) {
return o1
+o2
;
}
}
public class Divide implements strategy{
@Override
public int operate(int o1
, int o2
) {
return o1
/ o2
;
}
}
测试对象
public class TestObject {
private strategy strategy
;
public TestObject(strategy strategy
){
this.strategy
= strategy
;
}
public int executeStrategy(int num1
, int num2
){
return strategy
.operate(num1
, num2
);
}
}
测试结果
public class Test {
public static void main(String
[] args
) {
TestObject context
= new TestObject(new Add());
System
.out
.println("15 + 5 = " + context
.executeStrategy(15, 5));
context
= new TestObject(new Divide());
System
.out
.println("15 / 5 = " + context
.executeStrategy(15, 5));
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-42100.html