铁匠 铁匠
首页
golang
java
架构
常用算法
  • Java
  • nginx
  • 系统运维
  • 系统安全
  • mysql
  • redis
参考文档
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

铁匠

不予评判的专注当下
首页
golang
java
架构
常用算法
  • Java
  • nginx
  • 系统运维
  • 系统安全
  • mysql
  • redis
参考文档
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 概览

  • 设计模式

    • 软件设计原则
    • 创建型

    • 结构型

      • 装饰器模式
      • 委派模式
      • 代理模式
    • 行为型

  • 性能优化

  • 分布式

  • 网关

  • 流量治理

  • 数据治理

  • 云原生

  • 架构
  • 设计模式
  • 结构型
xugaoyi
2023-01-03

装饰器模式

通过装饰器模式,可以通过多个类包装在一起,组合多个功能,实现不同功能需求可拔插。

例:一个 redis 操作类,需要实现以下几个功能。

  1. 执行 redis 命令
  2. 统计耗时
  3. 链路监控打点

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

测试类

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
#装饰器模式
Last Updated: 2024/04/23, 01:30:37
工厂模式
委派模式

← 工厂模式 委派模式→

最近更新
01
go-kit学习指南 - 多协议支持
04-19
02
go-kit学习指南 - 中间件
04-19
03
go-kit开发微服务 - 服务注册与发现
04-19
更多文章>
Theme by Vdoing | Copyright © 2016-2024 铁匠 | 粤ICP备15021633号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式