装饰器模式
通过装饰器模式,可以通过多个类包装在一起,组合多个功能,实现不同功能需求可拔插。
例:一个 redis 操作类,需要实现以下几个功能。
- 执行 redis 命令
- 统计耗时
- 链路监控打点
public interface RedisClient {
void exec(String cmd);
}
public class DefaultRedisClient implements RedisClient {
@Override
public void exec(final String cmd) {
System.out.println("执行 redis 命令: " + cmd);
}
}
public class TimeCostRedisClient implements RedisClient {
// 被装饰对象
private final RedisClient decorator;
public TimeCostRedisClient(final RedisClient decorator) {
this.decorator = decorator;
}
@Override
public void exec(final String cmd) {
final long start = System.currentTimeMillis();
decorator.exec(cmd);
final long end = System.currentTimeMillis();
System.out.println("执行 redis 命令耗时: " + (end - start) + "ms");
}
}
public class TraceRedisClient implements RedisClient {
// 被装饰对象
private final RedisClient decorator;
public TraceRedisClient(final RedisClient decorator) {
this.decorator = decorator;
}
@Override
public void exec(final String cmd) {
final String uuid = UUID.randomUUID().toString();
System.out.println("链路监控开始: " + uuid);
decorator.exec(cmd);
System.out.println("链路监控结束: " + uuid);
}
}
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
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
测试类
public class RedisApp {
public static void main(String[] args) {
final RedisClient client = new DefaultRedisClient();
final TimeCostRedisClient timeCostRedisClient = new TimeCostRedisClient(client);
final TraceRedisClient traceRedisClient = new TraceRedisClient(timeCostRedisClient);
traceRedisClient.exec("set hello world");
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Last Updated: 2024/04/23, 01:30:37