1 minute read

use abstract factory if you need platform independence, for example if you have an api that creates buttons and you need to modify the library so that you can use it to create buttons wether you are on the windows platform or the mac platform.


from
http://www.vincehuston.org/dp/abstract_factory.html

Intent

  • Provide an interface for creating families of related or dependent objects without specifying their concrete classes. [GoF, p87]
  • A hierarchy that encapsulates: many possible "platforms", and the construction of a suite of "products".
  • The new operator considered harmful.

Check list

  1. Decide if "platform independence" and creation services are the current source of pain.
  2. Map out a matrix of "platforms" versus "products".
  3. Define a factory interface that consists of a factory method per product.
  4. Define a factory derived class for each platform that encapsulates all references to the new operator.
  5. The client should retire all references to new, and use the factory methods to create the product objects.
from
http://www.go4expert.com/forums/showthread.php?t=5127

We have a requirement where we need to create control library and the same library supports multiple platforms but the client code should not be changed if we import from one operating system to the other.

The solution is
The client uses the GuiFactory to get the required factory of the supported operating system and calls the same Show Method. Now depending on the platform we change the factory but the client implementation remains the same. If support for new operating system is to be added we need the new factory and the exact implementation of the buttons and without changing the existing code we can support the new platform.

from wikipedia
/*
* GUIFactory example
*/
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();
}
}


abstract class Button {
public abstract void paint();
}


class WinButton extends Button {
public void paint() {
System.out.println("I'm a WinButton: ");
}
}


class OSXButton extends Button {
public void paint() {
System.out.println("I'm an OSXButton: ");
}
}


public class Application {
public static void main(String[] args) {
GUIFactory factory = GUIFactory.getFactory();
Button button = factory.createButton();
button.paint();
}
// Output is either:
// "I'm a WinButton:"
// or:
// "I'm an OSXButton:"
}

Comments