It is a design pattern which creates objects at run time. It makes the user to develop objects. Even, it does not specify the exact class.
Program implementation:
Here, an interface Fruit is created with findColor() member
function.
- Two more classes are created using this interface. One is for Apple class and another one is guava.
- A new class “FruitBasket” is developed with a member function getFruit().
- The main class “FruitEg” is written with main() function.
- ‘findColor()’ – This function displays the colour of the fruit.
- ‘getFruit()’ – it gets the type of fruit. Using a if loop, check for fruit type and create the new object.
- ‘main()’ – this function creates the object for fruit class and call the findColor().
Program:
interface Shape {
void
findCorners();
}
public void
findCorners() {
System.out.println("Square has four Corners");
}
}
public void
findCorners() {
System.out.println("Triangle has three Corners");
}
}
public static
Shape getShape(String type) {
if
(type.equalsIgnoreCase("Square")) return new Square();
else if
(type.equalsIgnoreCase("Triangle")) return new Triangle();
return null;
}
}
public static void
main(String[] args) {
Shape myshape
= Shapes.getShape("Square");
myshape.findCorners();
}
}
Output:
Compile and run the program to get the output.
C:\raji\blog>javac ShapesEg.java
C:\raji\blog>java ShapesEg
Square has four Corners
This design Pattern is useful for frameworks.
That’s it. The Java Program to implement Factory Design
Pattern was written and executed successfully. Hope, this code is useful to
you.
No comments:
Post a Comment