Gowri Shankar
Gowri Shankar

Reputation: 161

Custom Factory Pattern Implementation

I am about to implement a factory pattern in java. I have a map like HashMap in a factory where I would add all the concrete implementations with a key of my choice. The key is defined by a abstract method getImplName() in the MyAbstract claass.

My requirement is when somebody extends MyAbstractClass and defines getImplName() , the key value pair must be automatically added to the factory map, instead of a code which manually does this. Is this possible ? I was thinking using custom annotations. Let me know your suggestions

Upvotes: 0

Views: 305

Answers (2)

Yair Zaslavsky
Yair Zaslavsky

Reputation: 4137

There is a debate in whether the factory elements should recognize the factory method.
I would recommend on the following approach if you want your elements to recognize the factory:

public abstract class MyAbstractClass {
  public MyAbstractClass(MyFactory factory) {
       factory.addElement(getImplName(),this);
  }

  public abstract String getImplName();
}

public class MyTestClass extends MyAbstractClass {
  public MyTestClass(MyFactory factory) {
    super(factory);
  }
}

Where MyFactory is a factory that has a HashMap as internal field
This way the programmer that extends MyAbstractClass is forced to provide a CTOR that by calling to the super class CTOR will add the object of the class to the factory.

Upvotes: 0

John Kane
John Kane

Reputation: 4443

In the constructor of your abstract class you should be able to call getImplName() and add it to your map (assuming there is one known instance of your map otherwise that would need to be passed in).

Or you could add parameters in your constructor to take in the values that you need.

Upvotes: 2

Related Questions