策略模式

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
//策略类
public abstract class Strategy {
public abstract void algorithmInterface();
}


//策略A 和 策略B
public class StrategyA extends Strategy{

@Override
public void algorithmInterface() {
System.out.println("算法A 的思想");
}
}


// 策略B
public class StrategyB extends Strategy{

@Override
public void algorithmInterface() {
System.out.println("算法B 的思想");
}
}


// 策略的执行对象
public class Context {

Strategy strategy;

public Context(Strategy strategy){
this.strategy = strategy;
}

public void contextInterFace(){
strategy.algorithmInterface();
}
}

//客户端
public class Client {


public static void main(String[] args) {
Context context;
context = new Context(new StrategyA());
context.contextInterFace();
context = new Context(new StrategyB());
context.contextInterFace();
}

}
Donate comment here