Factory Design Pattern
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();
class Square implements Shape {
public void findCorners() {
[Link]("Square has four Corners");
class Triangle implements Shape {
public void findCorners() {
[Link]("Triangle has three Corners");
}
class Shapes {
public static Shape getShape(String type) {
if ([Link]("Square")) return new Square();
else if ([Link]("Triangle")) return new Triangle();
return null;
public class ShapesEg {
public static void main(String[] args) {
Shape myshape = [Link]("Square");
[Link]();
Output:
Compile and run the program to get the output.
C:\raji\blog>javac [Link]
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.
📌 Used In: Object creation in frameworks like Spring Boot.