Use of the pattern makes it possible to interchange concrete class without changing the code that use them, even at runtime. However employment of this pattern, as with similar design patterns incurs the risk of unnecessary complexity and extra work in the initial writing of code.
The pattern is also used for to support other patterns such as the builder pattern.
The ClassFactory[?] class is an implementation of the factory in the Java standard library[?].
How to use it The factory determines the actual concrete type of object to be created, and it is here that the object is actually created (in C++, for instance, via the new operator). However, the factory only returns an abstract pointer (or wrapper class) to the created concrete object.
This insulates client code from object creation by having clients ask a factory object to create an object of the desired abstract type and to return an abstract pointer to the object.
As the factory only returns an abstract pointer, the client code (which requested the object from the factory) does not know - and is not burdened by - the actual concrete type of the object which was just created. In particular, this means:
/* * GUIFactory example in C# */
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:GUIFactory { public override Button createButton() { return(new WinButton()); } }
class OSXFactory:GUIFactory { public override Button createButton() { return(new OSXButton()); } }
abstract class Button { public string caption; public abstract void paint(); }
class WinButton:Button { public override void paint() { Console.WriteLine("I'm a WinButton: "+caption); } }
class OSXButton:Button { public override void paint() { Console.WriteLine("I'm a OSXButton: "+caption); } }
class Application { static void Main(string[] args) { GUIFactory aFactory = GUIFactory.getFactory(); Button aButton = aFactory.createButton(); aButton.caption = "Play"; aButton.paint(); } //output is //I'm a WinButton: Play //or //I'm a OSXButton: Play }
Search Encyclopedia
|
Featured Article
|