提问人:Rashhh 提问时间:9/1/2023 更新时间:9/21/2023 访问量:37
想要实现基于配置将数据保存到 DB 或 Kafka 的设计模式
Want to implement design pattern to save data to DB or Kafka based on configuration
问:
我想实现一种设计模式,根据配置将数据保存到 DB 或 Kafka。例如,如果配置值为 isDB=1,则保存到数据库,否则保存到 Kafka。
我正在考虑使用中介模式实现它,但在实现部分不是很确定。
答:
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 开箱即用的库)来注册正确的实现。
如果您希望在运行时做出此选择,情况当然会有所不同。在这种情况下,我会使用策略或工厂模式。
评论
IStorage storage = DB == 1 ? new DBStorage() : new KafkaStorage();