Java Factory Method is a creational design pattern used by java developers. what it basically does is it instantiates objects from a set of classes by considering a certain logic. That is creating an object without specifying the exact class of object that will be created. This is quite simple. Let's see how we can do this.
Say for an example we have a shape interface
public interface Shape{
void drawShape();
}
Now lets say we have two classes that implement the interface called Triangle and Square.
public class Triangle implements Shape{
public void drawShape(){
System.out.println("drawing three points and joining them");
}
}
public class Square implements Shape{
public void drawShape(){
System.out.println("drawing four points and joining them");
}
}
Now lets create the ShapeFactory class that is used to instantiate a shape.
public class ShapeFactory{
public Shape getShape(int numberOfEdges){
if(numberOfEdges==3)
return new Triangle();
if(numberOfEdges==4)
return new Square();
return null;//just to make the compiler happy ;)
}
}
Now let's see how to create a new square or a triangle. create a new class ShapeManager.
public class ShapeManager{
public static void main(String[] args){
ShapeFactory factory = new ShapeFactory();
Shape triangle = factory.getShape(3);//note that the object will be a triangle since the //parameter is 3
}
}
This is simply what happens in a factory method. You do not directly call "new"
key word to create an instance of shape. Instead you use a factory method to get an instance.
No comments:
Post a Comment