Abstract factory pattern

From Wikipedia, the free encyclopedia

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.

An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (eg. createLetter() and createResume()). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter() and createResume() that would create a corresponding object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class like Letter or Resume of which the client is aware. The client code would get an appropriate instantiation of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme. (They would all be fancy or modern objects.) The client would need to know how to handle only the abstract Letter or Resume class, not the specific version that it got from the concrete factory.

In software development, a Factory is the location in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage. This allows for new derived types to be introduced with no change to the code that uses the base object.

Use of this pattern makes it possible to interchange concrete classes without changing the code that uses 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.

Contents

[edit] 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, by the new operator). However, the factory only returns an abstract pointer 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:

  • The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations relating to the concrete type. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.
  • Adding new concrete types is done by modifying the client code to use a different factory, a modification which is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before - thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object.

And this is...

[edit] Structure

The class diagram of this design pattern is as shown below:

[edit] Examples

[edit] C++

#include <memory>
using std::auto_ptr;

class Control { };

class PushControl : public Control { };

class Factory {
 public:
   // Returns Factory subclass based on classKey.  Each
   // subclass has its own getControl() implementation.
   // This will be implemented after the subclasses have
   // been declared.
   static auto_ptr<Factory> getFactory(int classKey);
   virtual auto_ptr<Control> getControl() const = 0;
};

class ControlFactory : public Factory {
public:
   virtual auto_ptr<Control> getControl() const {
      return auto_ptr<Control>(new PushControl());
   }
};

auto_ptr<Factory> Factory::getFactory(int classKey) {
  // Insert conditional logic here.  Sample:
  switch(classKey) {
    default:
      return auto_ptr<Factory>(new ControlFactory());
  }
}

[edit] C#

/*
* 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: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
}

[edit] Java

/*
* 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());
    }
}

public abstract class Button  {
    private String caption;
    public abstract void paint();
    
    public String getCaption(){
        return caption;
    }
    public void setCaption(String caption){
        this.caption = caption;
    }
}

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

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

public class Application {
    public static void main(String[] args) {
        GUIFactory aFactory = GUIFactory.getFactory();
        Button aButton = aFactory.createButton();
        aButton.setCaption("Play");
        aButton.paint();
    }
    //output is
    //I'm a WinButton: Play
    //or
    //I'm a OSXButton: Play
}

[edit] Perl

# GUIFactory example on Perl

package GUIFactory;

sub getFactory($$) {
        shift; # skip class
        my $toolkit = shift;
        if ($toolkit eq 'GTK') {
            return(GtkFactory->new);
        } else {
            return(TkFactory->new);
        }
}

package GtkFactory;
use base 'GUIFactory';
 
sub new {
    bless({}, shift);
}

sub createButton {
        return(GtkButton->new);
}

package TkFactory;
use base 'GUIFactory';

sub new {
        bless({}, shift);
}

sub createButton() {
        return(TkButton->new);
}

package Button;

sub new {
        $class = shift;
        my $self = {};
        $self{caption} = ;
        bless($self, $class);
        return $self;
}

package GtkButton;
use base 'Button';

sub paint() {
       print "I'm a GtkButton\n";
}

package TkButton;
use base 'Button';

sub paint() {
       print "I'm a TkButton\n";
}

package main;

my $aFactory = GUIFactory->getFactory;
my $aButton = $aFactory->createButton;
$aButton->{caption} = "Play";
$aButton->paint();

[edit] Visual Prolog

interface guiFactory
    predicates
        createButton : () -> button NewButton.
        createEdit : () -> edit Edit.
end interface guiFactory
class winFactory : guiFactory
end class winFactory

implement winFactory
    clauses
        createButton() = winButton::new().
    clauses
        createEdit() = winEdit::new().
end implement winFactory
class osxFactory : guiFactory
end class osxFactory

implement osxFactory
    clauses
        createButton() = osxButton::new().
    clauses
        createEdit() = osxEdit::new().
end implement osxFactory

(The goal here is just for illustrative purposes; in a real program the GUI system would have to be initialized, and the button must be drawn somewhere.)

goal
    if 1 = config::getAttribute("OS_TYPE") then
        GuiFactory = winFactory::new()
    else
        GuiFactory = osxFactory::new()
    end if,
    Button = GuiFactory:createButton(),
    Button:setText("Play"),
    Button:paint().

[edit] See also