Factory Pattern is one of the most used design patterns in Java. It is an
Creational Pattern, providing one of the best ways to create an object. The pattern enables the code to choose which implementation to call at run time based on arguments provided to the Factory. Thus helping to create generic and maintainable code. The pattern also allows the developer the ease of adding new types of implementations without changing the old code.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
The demo code shown below demonstrates Pizza variations and based on the argument type passed to it, the factory will return the type of Pizza requested for.
For demo purpose, the code only shows for Cheese, Veg and Fresh Pan Pizza only.
Pros and Cons:
- Allows you to hide implementation of an application seam (the core interfaces that make up your application)
- Allows you to easily test the seam of an application (that is to mock/stub) certain parts of your application so you can build and test the other parts
- Allows you to change the design of your application more readily, this is known as loose coupling
- Makes code more difficult to read as all of your code is behind an abstraction that may in turn hide abstractions.
- Can be classed as an anti-pattern when it is incorrectly used, for example some people use it to wire up a whole application when using an IOC container, instead use Dependency Injection.