Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] Support for factory methods #3514

Open
sureshcentral opened this issue Sep 28, 2023 · 1 comment
Open

[FEATURE] Support for factory methods #3514

sureshcentral opened this issue Sep 28, 2023 · 1 comment

Comments

@sureshcentral
Copy link

@factory creates a factory method that can create different implementations:

Usage:

@Factory(HexagonImpl.class, TrianglImple.class)
interface Shape {
  ...
}

// Elsewhere ...
public class HexagonImpl implements Shape { ... }
public class TriangleImpl implements Shape { ... }

// Usage:
// Lombok creates a hidden 'factory' object in the interface Shape.
// The factory object returns a specific implementation.
Shape s = Shape.factory.create(Shape.Type.HEXAGON, ...params);

This is mostly useful for the so-called "sealed factories", where the
implementations types are known at compile time.

Implementation:

Shape.java:

// @Factory({TriangleImpl.class, HexagonImpl.class})
public interface Shape {
  /* Business methods. */
  int computeArea();

  /* ========= Generated by Lombok ========= */
  enum Type {TRIANGLE, HEXAGON}; // Enum generated by stripping out 'Impl' from the specified impl classes in the @Factory annotation.
  static final ShapeFactory factory = ShapeFactory.instance;
  class ShapeFactory {
    private static final ShapeFactory instance = new ShapeFactory();
    private ShapeFactory() {}
    public Shape create(Shape.Type type, Map<String, ?> properties) {
      switch (type) {
        case TRIANGLE:
          return new TriangleImpl(properties);
        case HEXAGON:
          return new HexagonImpl(properties);
      }
      throw new IllegalArgumentException("Unknown shape type: " + type);
    }
  }
  /* ========= End generated ========= */
}

TriangleImpl.java:

class TriangleImpl implements Shape {

  TriangleImpl(Map<String,?> properties) {
  }

  @Override
  public int computeArea() {
    // TODO
    return 0;
  }
}

HexagonImpl.java:

class HexagonImpl implements Shape {
  HexagonImpl(Map<String,?> properties) {
  }

  @Override
  public int computeArea() {
    // TODO
    return 0;
  }
}

Usage:

import Shape;

public class FactoryExample {
  public static void main() {
    Shape hex = Shape.factory.create(Shape.Type.HEXAGON, null);
  }
}
@rzwitserloot
Copy link
Collaborator

This doesn't strike me as boilerplate. Or rather, it strikes me as a feature that isn't going to have any users except 1 (you).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants