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

48 Views Asked by At

I want to implement a design pattern to save data to DB or Kafka based on the configuration. For example if config value isDB=1 then save to DB else save to Kafka.

I was thinking to implement it using mediator pattern but not very sure on implementation part.

1

There are 1 best solutions below

0
David Guida On

you need to implement those two persistence mechanisms using a common interface. Something like this:

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

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

at bootstrap time, you can read from a config file which persistence system you want and use a Dependency Injection library (like the one coming out of the box from .NET) to register the proper implementation.

Things would be of course different if you want this choice to be made at runtime instead. In that case I would use either the Strategy or the Factory pattern.