The Factory Pattern in Scala
The factory method is used to offer a single interface to instantiate one of the multiple classes. In the Factory pattern, the objective is to make the object in such a way that it does not expose to the creation logic to the Client and can always refer to a newly created object with the help of a common interface.
Let’s try to understand it with an example.
Assume that we need to create a library for a Car Purchase Application. The library is supposed to give three choices of cars types.
We are following an object-oriented design, and hence we decided to create three different classes. One for each car type. We also want to provide methods to get the booking price, Brands, and availability. All three classes will implement their methods individually but we have to decide on a simple method to create a Car object. So that all the cars can be purchased using the same method. Here is an example of how we want to book a car. the first statement returns an instance of a Standard car. the second statement returns a Deluxe Car, and the third one gives a Luxury Car. we are in this case offering one single method to create a variety of objects. the method Car here is a factory of Cars. we can book whatever type of car we need and as many as we want. this type of object creation makes programming very easy and the codes compact. one need not worry about different classes for different kinds of cars. That’s what a factory method is all about.
The factory method thus helps a lot in making programming concepts easier. In this way, we can always save the codespace and the number of classes if declaring multiple objects of same type with some dissimilarities.