According to my understanding on factory-method, factory should always return a new
instance, meaning no cache, So in essence, every time when the factory method is called, there should always be a new
instance returned, otherwise, it would not be a factory method pattern. For instance, the following code is not a factory:
public class UserManagementActionListenerFactory extends AbstractListenerFactory {
private static final String ENABLE_USER = "enableUser";
private static final String DISABLE_USER = "disableUser";
private static final String DELETE_USER = "deleteUser";
private static final String CONVERT_USER = "convertUser";
private Map<String,ActionListener> mapper;
public ActionListenerMapping() {
mapper = registerListeners();
}
private Map<String, ActionListener> registerListeners() {
Map<String,ActionListener> actionListenerMap = new HashMap<>();
actionListenerMap.put(ENABLE_USER, new EnableActionListener());
actionListenerMap.put(DISABLE_USER, new DisableActionListener());
actionListenerMap.put(DELETE_USER, new DeleteActionListener());
actionListenerMap.put(CONVERT_USER, new ConvertUserActionListener());
return actionListenerMap;
}
@Override
ActionListener getActionListener(String s) {
return mapper.get(s);
}
}
The UserManagementActionListenerFactory
is used in a bean called UserManagementBean
:
public class UserManagementBean {
AbstractActionListenerFactory factory;
@PostConstruct
public init() {
factory = new UserManagementActionListenerFactory();
}
//... irelevant code
public void handleActionEvent(ActionEvent e) {
String componentId = e.getComponent().getId();
factory.getActionListener(componentId).processAction(e);
}
}
As this ActionListenerMapper
initialized all the concrete subclasses of ActionListener
when being constructed, then every time the getActionListener(s)
is called, it always returns a cached ActionListener instance. Please tell here if my understanding is wrong
However, in first item of the book Effective Java:
A second advantage of static factory methods is that, unlike constructors, they are not required to create a new new object each time they're invoked.
Moreover, Effective Java also told:
Note that a static factory method is not the same as the Factory Method pattern from Design Patterns [Gamma95]
Question: Usually should a factory method always return a new instance
instance?