Abstract factory or just a factory in Java

The explanation of the abstract factory pattern:

"A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software would create a concrete implementation of the abstract factory and then use the generic interfaces to create the concrete objects that are part of the theme. The client does not know (nor care) about which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from its general usage." (from wikipedia) suggest the introduction of an abstract factory, which is subclassed by concrete realization. Every concrete factory cares about the construction of a concrete product. A simple example would be:


/* * GUIFactory example */

public abstract class GUIFactory {

public static GUIFactory getFactory() {

int sys = readFromConfigFile("OS_TYPE");

if (sys == 0) {

return(new WinFactory());

} else {

return(new OSXFactory()); }

}

public abstract Button createButton();

}

class WinFactory extends GUIFactory {

public Button createButton() {

return(new WinButton());

}

}

class OSXFactory extends GUIFactory {

public Button createButton() {

return(new OSXButton());

}

}

(also borrowed from wikipedia :-)).

But in Java we could provide even simpler and more generic extensible solution:

public class GUIFactory {

public final static GUIFactory instance = null;

public static GUIFactory getFactory() {

if(instance == null)

 instance = new GUIFactory();

return instance;

}

public Button createButton() {

String fullyQualifiedProductName = readFromConfigFile("BUTTON_TYPE");

return (Button)Class.forName(fullyQualifiedName).newInstance();

//Exceptionhandling...

}

}

In this case the factory is totally independent on the concrete product, which can be easily configured. Because of dynamic configuration the typesafety of the product can be only checked at the runtime - but you gain the flexibility. Instead of "home grown" implementation, also standalone IoC containers can be used to inject a product. In that case the factory belongs to that framework and do not have to be implemented in the scope of a project.

The Abstract Factory pattern is only interesting, in case the creation of different products is different (e.g. the constructor's signature or the way how the product are created  is different).


Cloudy Jakarta EE and MicroProfile: Microservices, Clouds and Beyond Jakarta EE / MicroProfile airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License