Decorator design pattern

Amr elshaer
2 min readApr 28, 2021

“Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.”

For decorator design patterns in the weather system, I will simplify content in the console app.

First Task is we want to add a page that takes the country’s name and gives the current weather in this country so we will make a list that contains all-weather countries as DB like this

and IWeatherSerivce

and add WeatherService to implement the IWeatherService

and in the program.cs call WeatherService

IWeatherService weatherService = new WeatherService();
Console.WriteLine(weatherService.GetWeather(“US”));

Second Task is to log data when the client asks for weather,we can and logging in to the same implementation in GetWeather in WeatherService but we will violate the single responsibility principle and the open-closed principle so we will add a decorator class that implements IWeatherSerivce and composes IWeatherSerivce in the constructor like this.

and so in the program.cs will call LoggingService

Third Task we want to cache the result from the client so we will and another decorator class that implements IWeatherSerivce like Logging

and call-in program.cs

and so the decorator design pattern works like an onion :

--

--

Amr elshaer
Amr elshaer

Written by Amr elshaer

Software engineer | .Net ,C# ,Angular, Javascript

No responses yet