-
Notifications
You must be signed in to change notification settings - Fork 146
/
JavaExample16.java
65 lines (52 loc) · 1.18 KB
/
JavaExample16.java
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
59
60
61
62
63
64
65
package com.sw.kotlin.tip16;
public class JavaExample16 {
/**
* 定义策略接口
*/
public interface Strategy {
void doSth();
}
/**
* A策略
*/
public static class AStrategy implements Strategy {
@Override
public void doSth() {
System.out.println("Do A Strategy");
}
}
/**
* B策略
*/
public static class BStrategy implements Strategy {
@Override
public void doSth() {
System.out.println("Do B Strategy");
}
}
/**
* 策略实施者
*/
public static class Worker {
private Strategy strategy;
public Worker(Strategy strategy) {
this.strategy = strategy;
}
public void work() {
System.out.println("START");
if (strategy != null) {
strategy.doSth();
}
System.out.println("END");
}
}
/*
* 测试策略
* */
public void testStrategy() {
Worker worker1 = new Worker(new AStrategy());
Worker worker2 = new Worker(new BStrategy());
worker1.work();
worker2.work();
}
}