One real-world problem that can be solved by the Factory Design Pattern in Java is the creation of objects based on specific conditions or parameters. Let's consider a scenario in a software application for creating different types of shapes, such as circles, rectangles, and triangles.
Problem: In a graphics application, you need to create various shapes based on user input or configuration settings. Depending on the type of shape requested, the application needs to instantiate the appropriate object (Circle, Rectangle, or Triangle). Without the Factory Design Pattern, the code might have conditional statements to determine which type of object to create. This can lead to code duplication and make the codebase less maintainable, especially if new shapes are added in the future.
Solution using Factory Design Pattern: The Factory Design Pattern provides a way to create objects without specifying the exact class of object that will be created. Instead of directly instantiating objects using constructors, a factory method is used to create objects based on certain conditions.
// Shape interface representing different types of shapes
interface Shape {
void draw();
}
// Concrete implementations of Shape interface
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Rectangle");
}
}
class Triangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Triangle");
}
}
// ShapeFactory class responsible for creating Shape objects
class ShapeFactory {
// Factory method to create Shape objects based on input
public Shape createShape(String shapeType) {
if (shapeType.equalsIgnoreCase("circle")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("rectangle")) {
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("triangle")) {
return new Triangle();
}
return null; // Return null or throw exception for unsupported shape types
}
}
public class Main {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
// Create different shapes using the factory
Shape circle = shapeFactory.createShape("circle");
circle.draw(); // Output: Drawing Circle
Shape rectangle = shapeFactory.createShape("rectangle");
rectangle.draw(); // Output: Drawing Rectangle
Shape triangle = shapeFactory.createShape("triangle");
triangle.draw(); // Output: Drawing Triangle
}
}
..

1 Comments
Good topics
ReplyDelete