Java Factory Design Pattern

Android Development Training

Java Factory Design Pattern

The factory design pattern is a common design pattern used in software development, particularly in object-oriented programming languages like Java. The factory design pattern is a creational design pattern, which means that it deals with object creation.

The factory design pattern is a way to provide a common interface for creating objects without specifying the exact class of object that will be created. This allows the code that uses the objects to be independent of the specific implementation of the objects.

Here is an example of how the factory design pattern might be implemented in Java:

public interface Shape {
  void draw();
}

public class Circle implements Shape {
  @Override
  public void draw() {
    // code to draw a circle
  }
}

public class Rectangle implements Shape {
  @Override
  public void draw() {
    // code to draw a rectangle
  }
}

public class ShapeFactory {
  public static Shape getShape(String shapeType) {
    if (shapeType == null) {
      return null;
    }
    if (shapeType.equalsIgnoreCase("CIRCLE")) {
      return new Circle();
    } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
      return new Rectangle();
    }
    return null;
  }
}

In the example above, the ShapeFactory class provides a static method called getShape() that takes a shapeType as an input and returns an object of the specified Shape type. This allows the code that uses the ShapeFactory to create Shape objects without knowing the exact implementation of the objects.

The factory design pattern is a useful pattern to use in Java because it promotes loose coupling and code reuse. It allows you to create objects without specifying their exact class, which makes your code more flexible and easier to maintain.

Spread the love

Comments

Leave a Reply