Basic Factory Example
This program demonstrates Factory design pattern.
Problem Statement
Write a Java program to implement Factory pattern for creating shapes.
Source Code
| 1 | interface Shape { void draw(); } |
| 2 | class Circle implements Shape { public void draw(){ System.out.println("Circle drawn"); } } |
| 3 | class Rectangle implements Shape { public void draw(){ System.out.println("Rectangle drawn"); } } |
| 4 | class ShapeFactory { |
| 5 | public Shape getShape(String type){ |
| 6 | if(type.equalsIgnoreCase("Circle")) return new Circle(); |
| 7 | else if(type.equalsIgnoreCase("Rectangle")) return new Rectangle(); |
| 8 | return null; |
| 9 | } |
| 10 | } |
| 11 | public class FactoryBasic { |
| 12 | public static void main(String[] args) { |
| 13 | System.out.println("Eduinq Factory Basic"); |
| 14 | ShapeFactory sf=new ShapeFactory(); |
| 15 | Shape s1=sf.getShape("Circle"); |
| 16 | Shape s2=sf.getShape("Rectangle"); |
| 17 | s1.draw(); s2.draw(); |
| 18 | } |
| 19 | } |
Program Output
Eduinq Factory Basic Circle drawn Rectangle drawn
Explanation
Factory centralizes object creation. - Client requests object by type. - Factory returns appropriate subclass instance. - This promotes loose coupling and flexibility. Conclusion: Shows how to implement Factory pattern.