想要实现基于配置将数据保存到 DB 或 Kafka 的设计模式

Want to implement design pattern to save data to DB or Kafka based on configuration

提问人:Rashhh 提问时间:9/1/2023 更新时间:9/21/2023 访问量:37

问:

我想实现一种设计模式,根据配置将数据保存到 DB 或 Kafka。例如,如果配置值为 isDB=1,则保存到数据库,否则保存到 Kafka。

我正在考虑使用中介模式实现它,但在实现部分不是很确定。

C# 设计模式 适配器 中介

评论

0赞 Enigmativity 9/1/2023
我们不是设计或编码服务。请尝试自己实现中介模式,如果您遇到困难,请携带您编写的代码来这里,我们很乐意为您提供帮助。
2赞 Enigmativity 9/1/2023
这应该给你一个战斗的机会:.IStorage storage = DB == 1 ? new DBStorage() : new KafkaStorage();

答:

1赞 David Guida 9/21/2023 #1

您需要使用通用接口实现这两种持久性机制。像这样的东西:

interface IPersistence{
   Task SaveAsync(IEnumerable<Foo> entries);
}

class DbPersistence : IPersistence { /* implementation here */ }
class KafkaPersistence : IPersistence { /* implementation here */ }

在引导时,可以从配置文件中读取所需的持久性系统,并使用依赖项注入库(如 .NET 开箱即用的库)来注册正确的实现。

如果您希望在运行时做出此选择,情况当然会有所不同。在这种情况下,我会使用策略或工厂模式。