As a beginning, we start by checking whether our customer has a company contract. If so, we retrieve their requested grade of car and runs through the options to see if we have a match.
For this scenario, we have already a Car super-class, which can be extended by all car brands sub-classes (Tesla, Audi, Volkswagen, and Toyota). This allows us to utilize the common methods of the Car super-class to perform a mechanical service check, clean up the car, and put fuel on it.
All of the above mentioned steps have all be accomplished inside the main-method of our system, as can be seen from the code sample below.
Although this code sample solves the objective, it has multiple problems. Firstly, it is not desirable to have all the car selection and preparation logics at the same level of abstraction as where the customer is. We want that kind of logic hidden away from the customer so that they only see the ready and shiny car. In code practice we also want this logic hidden away in its own class, to avoid modifications, while working on other parts of the main-method.
Secondly, we also want each contract type to be handled individually. Let’s say that the rental service one day shut down their company contract agreement. In this case, we want to easily be able to remove the logics related to the company contracts, without jeopardizing changes anywhere else in the system.
With these issues in mind, let’s see what the factory pattern can do for us.