Implementing Weather Forecast using Facade Design Pattern in Python
Facade Design Patterns are design patterns in Python that provide a simple interface to a complex subsystem. When we look into the world around us, we can always find facade design patterns. An automobile is the best example: you don’t need to understand how the engine functions. To operate the engine, you are provided with a set of simple interfaces such as turn the key in the ignition to start an engine, making use of steering wheels to turn the wheels, and more. Let’s look into the advantages of the Facade Design Pattern. They are as follows:
- Maintains loose coupling between client and subsystems.
- Easier to use and test
- Provides a better and clearer API for the client code
- It wraps a complicated subsystem with a simple interface
Weather Forecast Implementation
Let’s get into the implementation section. In this application, we fetch the current temperature in a city. For this purpose, we use available API’s from openweathermap.org resources. Here, without using the facade design pattern, the client has to go through so many complicated tasks such as API call, parse and retrieve the necessary data, and converts from Kelvin to Celcius. It is easier If the client needs to call only one method to get the current temperature. That’s what we achieve through the facade design pattern.
Before getting into the source code, let’s look into the code design pattern.
In the above diagram, we have a subsystem consist of four modules. If the client, uses these modules directly, it will lose its flexibility. This is because, if any of the modules is changed, then the client code needs to be modified, which adds up additional complexities. While using a facade design pattern, the client uses a facade, where the facade calls the submodule and returns the necessary details to the client. This design is based on the principle of decomposition, where a complex system is split into smaller and simpler subsystems.
Let’s look into the functionality of each module.
- The WeatherRetriever class makes requests to the weather API endpoint and returns forecast data.
- The Crawler class crawls the data returned from WeatherRetriever class, decodes it in the JSON format, and fetches the temperature.
- The WeatherForecast class is responsible for storing the temperature data.
- Finally, the Converter class converts the temperature from Kelvin to Celsius
So today’s forecast is about 7.170000000000016 degrees
A facade design pattern provides a higher-level interface that simplifies the usage of subsystems. The facade design doesn’t add any new functionality, instead, it acts as a wrapper that provides flexibility in accessing complex subsystems.