android 开发设计模式---Strategy模式

假设我们要出去旅游,而去旅游出行的方式有很多,有步行,有坐火车,有坐飞机等等。而如果不使用任何模式,我们的代码可能就是这样子的。

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
public class TravelStrategy {
enum Strategy{
WALK,PLANE,SUBWAY
}
private Strategy strategy;
public TravelStrategy(Strategy strategy){
this.strategy=strategy;
}

public void travel(){
if(strategy==Strategy.WALK){
print("walk");
}else if(strategy==Strategy.PLANE){
print("plane");
}else if(strategy==Strategy.SUBWAY){
print("subway");
}
}

public void print(String str){
System.out.println("出行旅游的方式为:"+str);
}

public static void main(String[] args) {
TravelStrategy walk=new TravelStrategy(Strategy.WALK);
walk.travel();

TravelStrategy plane=new TravelStrategy(Strategy.PLANE);
plane.travel();

TravelStrategy subway=new TravelStrategy(Strategy.SUBWAY);
subway.travel();
}
}

这样做有一个致命的缺点,一旦出行的方式要增加,我们就不得不增加新的else if语句,而这违反了面向对象的原则之一,对修改封闭。而这时候,策略模式则可以完美的解决这一切。

首先,需要定义一个策略接口。

1
2
3
4

public interface Strategy {
void travel();
}

然后根据不同的出行方式实行对应的接口

1
2
3
4
5
6
7
8
public class WalkStrategy implements Strategy{

@Override
public void travel() {
System.out.println("walk");
}

}
1
2
3
4
5
6
7
8
public class PlaneStrategy implements Strategy{

@Override
public void travel() {
System.out.println("plane");
}

}
1
2
3
4
5
6
7
8
public class SubwayStrategy implements Strategy{

@Override
public void travel() {
System.out.println("subway");
}

}

此外还需要一个包装策略的类,并调用策略接口中的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class TravelContext {
Strategy strategy;

public Strategy getStrategy() {
return strategy;
}

public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}

public void travel() {
if (strategy != null) {
strategy.travel();
}
}
}

测试一下代码

1
2
3
4
5
6
7
8
9
10
11
public class Main {
public static void main(String[] args) {
TravelContext travelContext=new TravelContext();
travelContext.setStrategy(new PlaneStrategy());
travelContext.travel();

}
}

 

原文地址:https://www.cnblogs.com/spps/p/9866812.html