-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContext.java
More file actions
58 lines (50 loc) · 1.22 KB
/
Context.java
File metadata and controls
58 lines (50 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package design.strategy;
public class Context {
//持有抽象策略角色的引用,用于客户端调用
private Strategy strategy;
//获得策略类
public Strategy getStrategy() {
return strategy;
}
//设置所需策略
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
//根据设置的策略类返回对应的结果
public int getResult(int a,int b)
{
return strategy.strategy(a, b);
}
}
abstract class Strategy {
//定义抽象策略的方法
public abstract int strategy(int a,int b);
}
class AddStrategy extends Strategy {
//定义实现加法的策略方法
public int strategy(int a, int b)
{
return a+b;
}
}
class SubStrategy extends Strategy {
//定义减法的策略方法
public int strategy(int a, int b)
{
return a-b;
}
}
class MultiplyStrategy extends Strategy {
//定义乘法的策略方法
public int strategy(int a,int b)
{
return a*b;
}
}
class DivStrategy extends Strategy {
//定义除法的策略方法,这里为了简单就不考虑除数为零的情况了
public int strategy(int a,int b)
{
return a/b;
}
}