Use of Factory Pattern and its implementation:
There is a base abstract shape class.
and various subclasses like line, circle etc..
Now if you want to create object of line and circle at client or in your paint application you will write code like :
It is the most widely used pattern among all design patterns. Its falls under "Creational" design pattern category and encapsulates the object creation and instantiation logic from the client or framework who want to use it.
In simple words whenever you need an object of particular product you need not to create it via using new operator you just need to call factory to create it for yourself and you use is it via common interface or base abstract class reference.
For Example suppose you are working on paint application where you need to provide an option for drawing various shapes like line, circle etc. Each shape will have its draw method where all the drawing logic will be performed. We can create a factory for the same which will encapsulates the object creation and instantiation logic and will return the object for requested shape.
For more understanding lets have a scenario states below:In simple words whenever you need an object of particular product you need not to create it via using new operator you just need to call factory to create it for yourself and you use is it via common interface or base abstract class reference.
For Example suppose you are working on paint application where you need to provide an option for drawing various shapes like line, circle etc. Each shape will have its draw method where all the drawing logic will be performed. We can create a factory for the same which will encapsulates the object creation and instantiation logic and will return the object for requested shape.
There is a base abstract shape class.
public abstract class Shape { public abstract void draw (); }
and various subclasses like line, circle etc..
class Line extends Shape { public void draw () { // draw line } } class Circle extends Shape { public void draw () { // draw line } }
Now if you want to create object of line and circle at client or in your paint application you will write code like :