The Factory Design Pattern in Java is a creational pattern used to encapsulate the object creation logic. It allows you to create objects without specifying the exact class name, promoting loose coupling and scalability.
Real-Life Example:
Consider a Shape Factory that can create different types of shapes like Circle, Rectangle, and Square.
Code Implementation:
Java code:
// Step 1: Define a common interface for all products
interface Shape {
void draw();
}
// Step 2: Implement concrete classes for specific products
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Circle");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Rectangle");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Square");
}
}
// Step 3: Create the Factory Class
class ShapeFactory {
// Factory method to create objects
public static Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
switch (shapeType.toLowerCase()) {
case "circle":
return new Circle();
case "rectangle":
return new Rectangle();
case "square":
return new Square();
default:
throw new IllegalArgumentException("Unknown shape type: " + shapeType);
}
}
}
// Step 4: Client code
public class FactoryPatternDemo {
public static void main(String[] args) {
// Using the factory to create shapes
Shape shape1 = ShapeFactory.getShape("Circle");
shape1.draw(); // Output: Drawing a Circle
Shape shape2 = ShapeFactory.getShape("Rectangle");
shape2.draw(); // Output: Drawing a Rectangle
Shape shape3 = ShapeFactory.getShape("Square");
shape3.draw(); // Output: Drawing a Square
}
}
How It Works:
1.
Interface/Abstract Class: The Shape
interface provides a common contract for all shapes. 2. Concrete Classes: Circle
, Rectangle
, and Square
are concrete implementations of the Shape
interface. 3.Factory Class: ShapeFactory
centralizes the object creation logic. The client specifies the desired shape type, and the factory produces the corresponding object.
Advantages: 1.Encapsulation: The instantiation logic is encapsulated in the factory, making the client code simpler. 2.Scalability: Adding new shapes (e.g., Triangle
) requires only updating the factory, not the client code. 3.Loose Coupling: The client depends on the interface (Shape
), not the concrete classes.
- Get link
- X
- Other Apps
Labels:
factory design pattern example with code explanation in java.
How factory design pattern works
what are advantages of using factory design pattern
what is factory design pattern in software design
- Get link
- X
- Other Apps
Comments
Post a Comment