Factory Pattern with Polymorphism

This program integrates Factory pattern with polymorphism.

Problem Statement

Write a Java program where Factory creates Shape objects polymorphically.

Source Code

1 abstract class Shape { abstract void draw(); }
2 class Circle extends Shape { void draw(){ System.out.println("Eduinq Circle Drawn"); } }
3 class Rectangle extends Shape { void draw(){ System.out.println("Eduinq Rectangle Drawn"); } }
4 class ShapeFactory {
5 Shape getShape(String type){
6 if(type.equals("circle")) return new Circle();
7 else return new Rectangle();
8 }
9 }
10 public class FactoryPolymorphism {
11 public static void main(String[] args) {
12 System.out.println("Eduinq Factory Polymorphism");
13 ShapeFactory sf=new ShapeFactory();
14 Shape s1=sf.getShape("circle");
15 Shape s2=sf.getShape("rectangle");
16 s1.draw(); s2.draw();
17 }
18 }

Program Output

					Eduinq Factory Polymorphism
Eduinq Circle Drawn
Eduinq Rectangle Drawn
				

Explanation

Factory pattern creates objects without exposing instantiation logic. - Polymorphism ensures correct method execution based on object type. - This integration demonstrates design pattern synergy with OOP principles, widely used in enterprise systems for decoupling creation logic from usage. Conclusion: Shows Factory pattern with polymorphism.

Quick Links to Explore