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.
- Scala | Pattern Matching
- Using Extractors with Pattern Matching In Scala
- AngularJS | Factory Method
- Scala Tutorial – Learn Scala with Step By Step Guide
- HTML | SVG pattern
- How to create singleton design pattern in PHP 5 ?
- How to check a string begins with some given characters/pattern ?
- Scala | Either
- Set in Scala | Set-2
- Set in Scala | Set-1
- Scala Map
- Scala short &(x: Int): Int
- Python vs Scala
- Scala | Ranges
- Scala | Equals
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.