Now, you would have already noticed this pattern in my earlier posts in bits but this post is specific to this pattern only.
Simply put, “Factory Method” pattern is just a method which provides the flexibility of creating objects without the need to specifying which class to be created. This is essentially useful when we have a complex hierarchy of classes and runtime a decision is to be made as to which object type needs to be instantiated.
The factory pattern can be used when:
- Code can’t be reused creating multiple types of related objects.
- Need to encapsulate the functionality that is required to create a type of object.
- Want to manage the object from one place.
Now, I am sitting at Starbucks now, so lets take an example from here itself. Me, I like Chocolate Mocha and Java chip Frappe but Ritu, like only White chocolate Mocha.
Keeping aside that, if you can see, we have 3 different implementation of coffee and one factory method to create the object to order coffee and make it.
Lets look at this example in work!
All the above classes are created.
Lets see it in action.
Now for your reference as well, I have created the entire workspace and is available to download from HERE.