Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most effective way of writing a factory method? [closed]

In most of the cases when we write a factory method it is a bunch of if conditions which can keep on growing. What is the most effective way of writing such a method (with the least if conditions)?

public A createA(final String id) {
    if (id.equals("A1")) {
      return new A1();
    }
    else if (id.equals("A2")) {
      return new A2();
    }
    return null;
  }
like image 535
Malik Firose Avatar asked Dec 12 '22 06:12

Malik Firose


2 Answers

You could use a Map<String, Supplier<A>>:

Map<String, Supplier<A>> map = new HashMap<>();
map.put("A1", () -> new A1());
map.put("A2", () -> new A2());

...

public A createA(final String id) {
    Supplier<A> supplier = map.get(id);
    if (supplier != null) {
        return supplier.get();
    }
    throw new IllegalArgumentException("unknown id: " + id);
}

This uses a standard Java 8 Supplier interface, with a Java 8 lambda syntax, but you could of course define your own Supplier interface, and create instances using anonymous inner classes.

like image 179
JB Nizet Avatar answered Apr 20 '23 01:04

JB Nizet


I like a archetype map approach - just fill the archetypes up at some stage - either in a static block or the class constructor. Code looks roughly like this

  Map<String, A> archetypes;

  public A createA(final String id)
  {
     A a = archetypes.get(id);
     return (a!=null)?a.copy():null;
  }
like image 42
Michael Anderson Avatar answered Apr 19 '23 23:04

Michael Anderson