Following on from my previous post where I implemented a decorator pattern using .NET Core dependency injection I realised that I could use the same method to create a composite pattern in a developer-friendly way. Composite Pattern Similar to the decorator pattern, the Composite Pattern let's you wrap existing implementations of an interface to augment the functionality. The difference between the two is that the decorator wraps a single instance of the interface; a composite wraps many. interface IService { void DoSomething(string value); } class Decorator : IService { public Decorator(IService wrappedService) { //... } } class Composite : IService { public Composite(IEnumerable wrappedServices) { //... } } This is useful where you have a number of implementations of your service and you don't want dependent classes to know whether they should call one, some or all of them. For example, if you have a report generator that wants to send results to multiple sources you might implement several instances of IReporter: interface IReporter { void Send(IReport report); } class ConsoleReporter : IReporter { public void Send(IReport report) { //write details to console } } class TelemetryReporter : IReporter { public void Send(IReport report) { //write stats to a telemetry service } } class EmailReporter : IReporter { public void Send(IReport report) { //send a report email to stakeholders } } Your composite reporter would construct on all other implementations of IReporter and call them in order: class CompositeReporter : IReporter { private IEnumerable _reporters; public CompositeReporter(IEnumerable reporters) { _reporters = reporters; } public void Send(IReport report) { foreach (var reporter in _reporters) reporter.
I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too.
Stay tuned to my blog, twitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.
.NET Core,ASP.NET,c#,Core,Development,composite,design-patterns,software,software-development
Stay tuned to my blog, twitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.
This article is related to
.NET Core,ASP.NET,c#,Core,Development,composite,design-patterns,software,software-development
No comments:
Post a Comment