By using Static Factory Method we encapsulate the creation process of an object. We can use new() to create an Object from its constructor. Instead we use static method of a Factory to create the object. One main advantage of using Factory is that Factory can choose the correct implementation at runtime and create the right object. The caller of method can specify the desired behavior.
E.g. If we have a ShapeFactory with createShape(String type) method. Client can call ShapeFactory.createShape(“Circle”) to get a circular shape. ShapeFactory.createShape(“Square”) will return square shape. In this way, ShapeFactory knows how to create different shapes based on the input by caller.
Another use of Factory is in providing access to limited resources to a large set of users.
E.g. In ConnectionPool, we can limit the total number of connections that can be created as well as we can hide the implementation details of creating connection. Here ConnectionPool is the factory. Clients call static method ConnectionPool.getConnection().Read the full book at www.amazon.com