The factory method pattern

The factory method pattern basically specifies the interface to create an object without specifying its exact class. This pattern primarily focuses on creating only one type of object specified by the interface for the object to be created.

For example, in our application, we want to use a weather service to get the current weather of a given city. What we need is a reference to the weather service object, and what the factory method abstracts out is that we need a weather service reference without knowing where this actual object reference is coming from. For example, it can be from Yahoo weather, AccuWeather, or even a fake weather service object that can be used for testing.

In the section for .NET Core dependency injection, we used the IAirportFlightSchedulesFactory factory class, which creates the objects of the IAirportFlightSchedules interface, which the client code uses to get the list of all arrival flights.

Now let's say that we want to get a list of all arrival flights from Geneva airport. What we will do is use the GenevaAirportFlightSchedulesFactory class that implements the same interface IAirportFlightSchedulesFactory and creates the objects of type GenevaAirportFlightSchedules, which implements the same interface, IAirportFlightSchedules. Let's take a quick look at the code for this new Geneva factory:

    public class GenevaAirportFlightSchedulesFactory :
IAirportFlightSchedulesFactory
{
private ILogger _logger;

public GenevaAirportFlightSchedulesFactory(ILogger logger)
{
_logger = logger;
}

public IAirportFlightSchedules CreateAirportFlightSchedules()
{
return new GenevaAirportFlightSchedules(_logger);
}
}

Say, if we need flight schedules for a different airport, all we need to do is use the different factory to get the right service object, and in this way, no change is required in the client code at all.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.77.250