Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses
Let's take a practical example that illustrates the usage of this method. We have various UI elements can make a request that are React, Vue and Angular. We want to make the code extensible in that sense that the client code should not be changed in case of switching from one library to another.
First of all, we need to define an interface of concrete product so that the client code can use as below:
The client code should only know that any library could make the request call no matter what. Then we need to define a function to create a UI element like so
And finally, we need to implement couple of struct that satisfy the Request interface so that the client code can call upon
And voila 🎉, we have a complete implementation of Factory Method pattern in go. With this pattern in practice, the code is very extensible in the sense that the client code is loosely coupled to the library call. Hence, the potential change in the future due to requirement is totally at ease 😊
P/s: The accompany code is included in this PR 😊
Happy coding 😎