Abstract factory pattern

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.[1] In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client doesn't know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products.[1] This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.[2]

An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (e.g. 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 instance 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 only need to know how to handle the abstract Letter or Resume class, not the specific version that it got from the concrete factory.

A factory is the location of a concrete class in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage and to create families of related objects without having to depend on their concrete classes.[2] This allows for new derived types to be introduced with no change to the code that uses the base class.

Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at runtime. However, employment of this pattern, as with similar design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Additionally, higher levels of separation and abstraction can result in systems which are more difficult to debug and maintain.

Definition

The essence of the Abstract Factory Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes.".[3]

Usage

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.[4]

As the factory only returns an abstract pointer, the client code (that requested the object from the factory) does not know and is not burdened by the actual concrete type of the object that was just created. However, the type of a concrete object (and hence a concrete factory) is known by the abstract factory; for instance, the factory may read it from a configuration file. The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:

Structure

Rational Class Diagram

The method createButton on the GuiFactory interface returns objects of type Button. What implementation of Button is returned depends on which implementation of GuiFactory is handling the method call.

UML Class Diagram

Lepus3 chart (legend)

Pseudocode

It should render a button in either a Windows style or Mac OS X style depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.

interface Button is
  method paint()

interface GUIFactory is
  method createButton()
      output:  a button

class WinFactory implementing GUIFactory is
  method createButton() is
      output:  a Windows button
    Return a new WinButton

class OSXFactory implementing GUIFactory is
  method createButton() is
      output:  an OS X button
    Return a new OSXButton

class WinButton implementing Button is
  method paint() is
    Render a button in a Windows style

class OSXButton implementing Button is
  method paint() is
    Render a button in a Mac OS X style

class Application is
  constructor Application(factory) is
      input:  the GUIFactory factory used to create buttons
    Button button := factory.createButton()
    button.paint()

Read the configuration file
If the OS specified in the configuration file is Windows, then
  Construct a WinFactory
  Construct an Application with WinFactory
else
  Construct an OSXFactory
  Construct an Application with OSXFactory

C# Example

Abstract factory is the extension of basic Factory pattern. It provides Factory interfaces for creating a family of related classes. In other words, here I am declaring interfaces for Factories, which will in turn work in similar fashion as with Factories.

/*IVSR:Abstract factory pattern*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace DesignPatterns.AbstractFactory
{
    public class GenericFactory<T> 
        where T : new()
    {
        public T CreateObject()
        {
            return new T();
        }
    }
 
    public abstract class CarFactory
    {
        public abstract SportsCar CreateSportsCar();
        public abstract FamilyCar CreateFamilyCar();
    }
 
    public abstract class FamilyCar
    {
        public abstract void Speed(SportsCar abstractSportsCar);
    }
 
    public abstract class SportsCar
    {
    }
 
    public class MercedesFactory : CarFactory
    {
        public override SportsCar CreateSportsCar()
        {
            return new MercedesSportsCar();
        }
 
        public override FamilyCar CreateFamilyCar()
        {
            return new MercedesFamilyCar();
        }
    }
 
 
 
    class MercedesSportsCar : SportsCar
    {
    }
 
    class MercedesFamilyCar : FamilyCar
    {
        public override void Speed(SportsCar abstractSportsCar)
        {
            Console.WriteLine(GetType().Name + " is slower than "
                + abstractSportsCar.GetType().Name);
        }
    }
 
    public class Driver
    {
        private CarFactory _carFactory;
        private SportsCar _sportsCar;
        private FamilyCar _familyCar;
 
        public Driver(CarFactory carFactory)
        {
            _carFactory = carFactory;
            _sportsCar = _carFactory.CreateSportsCar();
            _familyCar = _carFactory.CreateFamilyCar();
        }
 
        public CarFactory CarFactory
        {
            get { return _carFactory; }
            set { _carFactory = value; }
        }
 
        public SportsCar SportsCar
        {
            get { return _sportsCar; }
        }
 
        public FamilyCar FamilyCar
        {
            get { return _familyCar; }
        }
 
        public void CompareSpeed()
        {
            FamilyCar.Speed(SportsCar);
        }
    }
}

The factory method is also implemented using common interface each of which returns objects.

//IVSR: Abstract factory using common interface
    public interface IPeopleFactory
    {
        IPeople GetPeople();
    }
 
    public class VillagersFactory : IPeopleFactory
    {
        public IPeople GetPeople()
        {
            return new Villagers();
        }
    }
 
    public interface IProductFactory
    {
        IProduct GetProduct();
    }
 
    public class AppleFactory : IProductFactory
    {
        public IProduct GetProduct()
        {
            return new IPhone();
        }
    }
 
    public abstract class AbstractFactory
    {
        public abstract IPeopleFactory GetPeopleFactory();
        public abstract IProductFactory GetProductFactory();
    }
 
    public class ConcreteFactory : AbstractFactory
    {
        public override IPeopleFactory GetPeopleFactory()
        {
            return new VillagersFactory ();
        }
 
        public override IProductFactory GetProductFactory()
        {
            return new AppleFactory ();
        }
    }

See also

References

  1. 1.0 1.1 Freeman, Eric; Freeman, Elisabeth; Kathy, Sierra; Bert, Bates (2004). Hendrickson, Mike; Loukides, Mike, eds. "Head First Design Patterns" (PAPERBACK) 1. O'REILLY. p. 156. ISBN 978-0-596-00712-6. Retrieved 2012-09-12.
  2. 2.0 2.1 Freeman, Eric; Freeman, Elisabeth; Kathy, Sierra; Bert, Bates (2004). Hendrickson, Mike; Loukides, Mike, eds. "Head First Design Patterns" (PAPERBACK) 1. O'REILLY. p. 162. ISBN 978-0-596-00712-6. Retrieved 2012-09-12.
  3. Gamma, Erich; Richard Helm; Ralph Johnson; John M. Vlissides (2009-10-23). "Design Patterns: Abstract Factory". informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
  4. Veeneman, David (2009-10-23). "Object Design for the Perplexed". The Code Project. Archived from the original on 2011-09-18. Retrieved 2012-05-16. The factory insulates the client from changes to the product or how it is created, and it can provide this insulation across objects derived from very different abstract interfaces.
  5. 5.0 5.1 "Abstract Factory: Implementation". OODesign.com. Retrieved 2012-05-16.

External links

The Wikibook Computer Science Design Patterns has a page on the topic of: Abstract Factory in action