Jump to content

Abstract factory pattern: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Java: Syntax error
 
(434 intermediate revisions by more than 100 users not shown)
Line 1: Line 1:
{{Short description|Software design pattern}}
A software [[Design pattern (computer science)|design pattern]], the '''Abstract Factory Pattern''' provides a way to encapsulate a group of individual [[factory object|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 [[Interface (computer science)|interface]]s to create the concrete [[Object (computer science)|object]]s that are part of the theme. The [[client (computing)|client]] does not know (or 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.
[[Image:Abstract factory UML.svg|UML class diagram|thumb|right|317x317px]]
The '''abstract factory pattern''' in [[software engineering]] is a design pattern that provides a way to create families of related objects without imposing their concrete classes, by encapsulating a group of individual [[factory object|factories]] that have a common theme without specifying their concrete classes.<ref name="abstract factory">{{cite book | last1 = Freeman | first1 = Eric | last2 = Robson | first2 = Elisabeth | last3 = Sierra | first3 = Kathy | last4 = Bates | first4 = Bert | editor1-last = Hendrickson | editor1-first = Mike | editor2-last = Loukides | editor2-first = Mike | year = 2004 | title = Head First Design Patterns | volume = 1 | page = 156 | publisher = O'REILLY | format = paperback | isbn = 978-0-596-00712-6 | access-date = 2012-09-12 | url = http://shop.oreilly.com/product/9780596007126.do
}}</ref> According to this pattern, a client software component creates a concrete implementation of the abstract factory and then uses the generic [[Interface (object-oriented programming)|interface]] of the factory to create the concrete [[Object (computer science)|object]]s that are part of the family. The [[client (computing)|client]] does not know which concrete objects it receives from each of these internal factories, as it uses only the generic interfaces of their products.<ref name="abstract factory" /> This [[software design pattern|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.<ref name="bullet points">{{cite book | last1 = Freeman | first1 = Eric | last2 = Robson | first2 = Elisabeth | last3 = Sierra | first3 = Kathy | last4 = Bates | first4 = Bert | editor1-last = Hendrickson | editor1-first = Mike | editor2-last = Loukides | editor2-first = Mike | year = 2004 | title = Head First Design Patterns | volume = 1 | page = 162 | publisher = O'REILLY | format = paperback | isbn = 978-0-596-00712-6 | access-date = 2012-09-12 | url = http://shop.oreilly.com/product/9780596007126.do
}}</ref>


Use of this pattern enables interchangeable concrete implementations without changing the code that uses them, even at [[Run time (program lifecycle phase)|runtime]]. However, employment of this pattern, as with similar [[Design pattern (computer science)|design pattern]]s, 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 that are more difficult to debug and maintain.
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 (computer science)|object]] like ''FancyLetter'' or ''ModernResume''. Each of these products is derived from a simple [[abstract class]] like ''Letter'' or ''Resume'' of which the [[client_(computing)|client]] is aware. The client code would get an appropriate [[instantiation]] of the ''DocumentCreator'' and call its [[factory method]]s. 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.


==Overview==
The abstract factory design pattern is one of the 23 patterns described in the 1994 ''[[Design Patterns]]'' book. It may be used to solve problems such as:<ref>{{cite web|title=The Abstract Factory design pattern - Problem, Solution, and Applicability|url=http://w3sdesign.com/?gr=c01&ugr=proble|website=w3sDesign.com|access-date=2017-08-11}}</ref>
* How can an application be independent of how its objects are created?
* How can a class be independent of how the objects that it requires are created?
* How can families of related or dependent objects be created?


Creating objects directly within the class that requires the objects is inflexible. Doing so commits the class to particular objects and makes it impossible to change the instantiation later without changing the class. It prevents the class from being reusable if other objects are required, and it makes the class difficult to test because real objects cannot be replaced with mock objects.


In [[software development]], a '''Factory''' is the location in the code at which [[object creation|objects are constructed]]. The intent in employing the pattern is to insulate the creation of objects from their usage. This allows for new [[derived type]]s to be introduced with no change to the code that uses the [[base class]].
A factory is the location of a concrete class in the code at which [[object creation|objects are constructed]]. Implementation of the pattern intends to insulate the creation of objects from their usage and to create families of related objects without depending on their concrete classes.<ref name="bullet points" /> This allows for new [[Subtyping|derived types]] to be introduced with no change to the code that uses the [[base class]].


The pattern describes how to solve such problems:
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 pattern (computer science)|design pattern]]s, may result in unnecessary complexity and extra work in the initial writing of code.
* [[Encapsulation (computer programming)|Encapsulate]] object creation in a separate (factory) object by defining and implementing an interface for creating objects.
* Delegate object creation to a factory object instead of creating objects directly.


This makes a class independent of how its objects are created. A class may be configured with a factory object, which it uses to create objects, and the factory object can be exchanged at runtime.
==How to use it==
{{See also|#UML diagram}}
The ''factory'' determines the actual ''concrete'' type of [[object (computer science)|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 [[object (computer science)|concrete object]].


==Definition==
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.
''Design Patterns'' describes the abstract factory pattern as "an interface for creating families of related or dependent objects without specifying their concrete classes."<ref name=":0">{{cite web | url = http://www.informit.com/ | title = Design Patterns: Abstract Factory | first = Erich | last = Gamma | author2 = Richard Helm | author3 = Ralph Johnson | author4 = John M. Vlissides | date = 2009-10-23 | publisher = informIT | archive-url = https://web.archive.org/web/20120516213805/http://www.informit.com/ | archive-date = 2012-05-16 | access-date = 2012-05-16 | quote = Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes. | url-status = bot: unknown }}</ref>


==Usage==
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. 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:
The factory determines the concrete type of object to be created, and it is here that the object is actually created. However, the factory only returns a reference (in Java, for instance, by the '''new''' [[operator (programming)|operator]]) or a [[pointer (computer programming)|pointer]] of an abstract type to the created concrete object.


This insulates client code from [[object creation]] by having clients request that a [[factory object]] create an object of the desired [[abstract type]] and return an abstract pointer to the object.<ref>{{cite web | url = http://www.codeproject.com/ | title = Object Design for the Perplexed | first = David | last = Veeneman | date = 2009-10-23 | publisher = The Code Project | archive-url = https://web.archive.org/web/20110221224616/http://www.codeproject.com/ | archive-date = 2011-02-21 | access-date = 2012-05-16 | quote = 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. | url-status = bot: unknown }}</ref>
* The client code has no knowledge whatsoever of the [[concrete]] [[type]], not needing to include any [[header file]]s or [[class]] [[declaration]]s 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 pattern|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.


An example is an abstract factory class <code>DocumentCreator</code> that provides interfaces to create a number of products (e.g., <code>createLetter()</code> and <code>createResume()</code>). The system would have any number of derived concrete versions of the <code>DocumentCreator</code> class such as<code>FancyDocumentCreator</code> or <code>ModernDocumentCreator</code>, each with a different implementation of <code>createLetter()</code> and <code>createResume()</code> that would create corresponding objects such as<code>FancyLetter</code> or <code>ModernResume</code>. Each of these products is derived from a simple [[abstract class]] such as<code>Letter</code> or <code>Resume</code> of which the client is aware. The client code would acquire an appropriate [[Instance (computer science)|instance]] of the <code>DocumentCreator</code> and call its [[factory method]]s. Each of the resulting objects would be created from the same <code>DocumentCreator</code> implementation and would share a common theme. The client would only need to know how to handle the abstract <code>Letter</code> or <code>Resume</code> class, not the specific version that was created by the concrete factory.
== Structure ==
The [[class diagram]] of this design pattern is as shown here:
[[Image:Abstract_factory.png]]
<!-- [[Image:Abstract factory UML.jpeg|center]] -->


As the factory only returns a reference or a pointer to an abstract type, the client code that requested the object from the factory is not aware of&mdash;and is not burdened by&mdash;the actual concrete type of the object that was created. However, the abstract factory knows the type of a concrete object (and hence a concrete factory). For instance, the factory may read the object's type from a configuration file. The client has no need to specify the type, as the type has already been specified in the configuration file. In particular, this means:
The [[Lepus3]] chart ([http://www.lepus.org.uk/ref/legend/legend.xml legend]) of this design pattern is as shown here:
[[Image:Abstract Factory in LePUS3.png]]


* The client code has no knowledge of the concrete [[Data type|type]], not needing to include any [[header file]]s or [[Class (computer science)|class]] [[Declaration (computer science)|declaration]]s related to it. 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|abstract interfaces]].<ref name="implementation">{{cite web | url = http://www.oodesign.com/abstract-factory-pattern.html | title = Abstract Factory: Implementation | publisher = OODesign.com | access-date = 2012-05-16
}}</ref>
* Adding new concrete types is performed by modifying the client code to use a different factory, a modification that 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. Doing so would require changing every location in the code where a new object is created as well as ensuring that all such code locations have knowledge of the new concrete type, for example, by including a concrete class header file. If all factory objects are stored globally in a [[singleton pattern|singleton]] object, and all client code passes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object.<ref name="implementation" />


== Structure ==
This class diagram does not emphasize the usage of abstract factory pattern in creating families of related or non related objects.


== Example ==
=== UML diagram ===
{{Plain image with caption|File:w3sDesign Abstract Factory Design Pattern UML.jpg|A sample UML class and sequence diagram for the abstract factory design pattern.
<ref>{{cite web|title=The Abstract Factory design pattern - Structure and Collaboration|url=http://w3sdesign.com/?gr=c01&ugr=struct|website=w3sDesign.com|access-date=2017-08-12}}</ref>|700px|align=left}}{{-}}
In the above [[Unified Modeling Language|UML]] [[class diagram]],
the <code>Client</code> class that requires <code>ProductA</code> and <code>ProductB</code> objects does not instantiate the <code>ProductA1</code> and <code>ProductB1</code> classes directly. Instead, the <code>Client</code> refers to the <code>AbstractFactory</code> interface for creating objects, which makes the <code>Client</code> independent of how the objects are created (which concrete classes are instantiated). The <code>Factory1</code> class implements the <code>AbstractFactory</code> interface by instantiating the <code>ProductA1</code> and <code>ProductB1</code> classes.


The [[Unified Modeling Language|UML]] [[sequence diagram]] shows the runtime interactions. The <code>Client</code> object calls <code>createProductA()</code> on the <code>Factory1</code> object, which creates and returns a <code>ProductA1</code> object. Thereafter, the <code>Client</code> calls <code>createProductB()</code> on <code>Factory1</code>, which creates and returns a <code>ProductB1</code> object.
=== Java ===
<source lang="java">


=== Variants ===
/* GUIFactory example -- */
The original structure of the abstract factory pattern, as defined in 1994 in ''[[Design Patterns]]'', is based on abstract classes for the abstract factory and the abstract products to be created. The concrete factories and products are classes that specialize the abstract classes using inheritance.<ref name=":0" />


A more recent structure of the pattern is based on interfaces that define the abstract factory and the abstract products to be created. This design uses native support for interfaces or protocols in mainstream programming languages to avoid inheritance. In this case, the concrete factories and products are classes that realize the interface by implementing it.<ref name="abstract factory" />
interface GUIFactory {
public Button createButton();
}


== Example ==
This C++11 implementation is based on the pre C++98 implementation in the book.


<syntaxhighlight lang="c++">
class WinFactory implements GUIFactory {
#include <iostream>
public Button createButton() {
return new WinButton();
}
}


enum Direction {North, South, East, West};


class MapSite {
class OSXFactory implements GUIFactory {
public:
public Button createButton() {
virtual void enter() = 0;
return new OSXButton();
virtual ~MapSite() = default;
}
}
};


class Room : public MapSite {
public:
Room() :roomNumber(0) {}
Room(int n) :roomNumber(n) {}
void setSide(Direction d, MapSite* ms) {
std::cout << "Room::setSide " << d << ' ' << ms << '\n';
}
virtual void enter() {}
Room(const Room&) = delete; // rule of three
Room& operator=(const Room&) = delete;
private:
int roomNumber;
};


class Wall : public MapSite {
public:
interface Button {
Wall() {}
public void paint();
virtual void enter() {}
}
};


class Door : public MapSite {
public:
Door(Room* r1 = nullptr, Room* r2 = nullptr)
:room1(r1), room2(r2) {}
virtual void enter() {}
Door(const Door&) = delete; // rule of three
Door& operator=(const Door&) = delete;
private:
Room* room1;
Room* room2;
};


class WinButton implements Button {
class Maze {
public void paint() {
public:
void addRoom(Room* r) {
System.out.println("I'm a WinButton");
std::cout << "Maze::addRoom " << r << '\n';
}
}
}
Room* roomNo(int) const {
return nullptr;
}
};


class MazeFactory {
public:
class OSXButton implements Button {
MazeFactory() = default;
public void paint() {
virtual ~MazeFactory() = default;
System.out.println("I'm an OSXButton");
}
}


virtual Maze* makeMaze() const {
return new Maze;
class Application {
}
public Application(GUIFactory factory){
virtual Wall* makeWall() const {
Button button = factory.createButton();
button.paint();
return new Wall;
}
}
virtual Room* makeRoom(int n) const {
}
return new Room(n);
}
virtual Door* makeDoor(Room* r1, Room* r2) const {
return new Door(r1, r2);
}
};

// If createMaze is passed an object as a parameter to use to create rooms, walls, and doors, then you can change the classes of rooms, walls, and doors by passing a different parameter. This is an example of the Abstract Factory (99) pattern.


public class ApplicationRunner {
class MazeGame {
public:
public static void main(String[] args) {
Maze* createMaze(MazeFactory& factory) {
new Application(createOsSpecificFactory());
Maze* aMaze = factory.makeMaze();
}
Room* r1 = factory.makeRoom(1);
Room* r2 = factory.makeRoom(2);
Door* aDoor = factory.makeDoor(r1, r2);
aMaze->addRoom(r1);
aMaze->addRoom(r2);
r1->setSide(North, factory.makeWall());
r1->setSide(East, aDoor);
r1->setSide(South, factory.makeWall());
r1->setSide(West, factory.makeWall());
r2->setSide(North, factory.makeWall());
r2->setSide(East, factory.makeWall());
r2->setSide(South, factory.makeWall());
r2->setSide(West, aDoor);
return aMaze;
}
};


int main() {
public static GUIFactory createOsSpecificFactory() {
MazeGame game;
int sys = readFromConfigFile("OS_TYPE");
MazeFactory factory;
if (sys == 0) {
game.createMaze(factory);
return new WinFactory();
} else {
return new OSXFactory();
}
}
}
}
</syntaxhighlight>


The program output is:
</source>
The output should be either "I'm a WinButton" or "I'm a OSXButton" 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.


<syntaxhighlight lang="output">
---------------------------------------
Maze::addRoom 0x1317ed0
Maze::addRoom 0x1317ef0
Room::setSide 0 0x1318340
Room::setSide 2 0x1317f10
Room::setSide 1 0x1318360
Room::setSide 3 0x1318380
Room::setSide 0 0x13183a0
Room::setSide 2 0x13183c0
Room::setSide 1 0x13183e0
Room::setSide 3 0x1317f10
</syntaxhighlight>


== See also ==
== See also ==
* [[Object creation]]
* [[Concrete class]]
* [[Concrete class]]
* [[Factory method pattern]]
* [[Factory method pattern]]
* [[Object creation]]
* [[Design pattern (computer science) | Design Pattern]]
* [[Software design pattern]]


==References==
== External links ==
{{Reflist}}
*[http://c2.com/cgi-bin/wiki?AbstractFactory Abstract Factory]
*[http://www.dofactory.com/Patterns/PatternAbstract.aspx Abstract Factory]
*[http://www.netobjectivesrepository.com/TheAbstractFactoryPattern Abstract Factory on the Net Objectives Repository]
*[http://www.fsw.com/Jt/Jt.htm Jt] J2EE Pattern Oriented Framework
*[http://www.lepus.org.uk/ref/companion/AbstractFactory.xml Abstract Factory in UML and in LePUS3] (a Design Description Language)


==External links==
{{Wikibooks|Computer Science Design Patterns|Abstract Factory|Abstract Factory in action}}
* {{Commons-inline}}
* [https://web.archive.org/web/20151101110755/http://www.patterns.pl/abstractfactory.html Abstract Factory] Abstract Factory implementation example


{{Design patterns}}


{{Design Patterns Patterns}}


[[Category:Software design patterns]]
[[Category:Software design patterns]]
<!-- Hidden categories below -->
[[Category:Articles with example Java code]]
[[Category:Articles with example C++ code]]

[[de:Abstrakte Fabrik]]
[[es:Abstract Factory (patrón de diseño)]]
[[fr:Fabrique abstraite (patron de conception)]]
[[ko:추상 팩토리 패턴]]
[[it:Abstract factory]]
[[ja:Abstract Factory パターン]]
[[pl:Wzorzec fabryki abstrakcyjnej]]
[[pt:Abstract Factory]]
[[ru:Абстрактная фабрика (шаблон проектирования)]]
[[th:Abstract factory pattern]]
[[vi:Abstract factory pattern]]
[[uk:Абстрактна фабрика (шаблон проектування)]]
[[zh:抽象工厂]]

Latest revision as of 06:42, 29 August 2024

UML class diagram

The abstract factory pattern in software engineering is a design pattern that provides a way to create families of related objects without imposing their concrete classes, by encapsulating a group of individual factories that have a common theme without specifying their concrete classes.[1] According to this pattern, a client software component 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 family. The client does not know which concrete objects it receives from each of these internal factories, as 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]

Use of this pattern enables interchangeable 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 that are more difficult to debug and maintain.

Overview

[edit]

The abstract factory design pattern is one of the 23 patterns described in the 1994 Design Patterns book. It may be used to solve problems such as:[3]

  • How can an application be independent of how its objects are created?
  • How can a class be independent of how the objects that it requires are created?
  • How can families of related or dependent objects be created?

Creating objects directly within the class that requires the objects is inflexible. Doing so commits the class to particular objects and makes it impossible to change the instantiation later without changing the class. It prevents the class from being reusable if other objects are required, and it makes the class difficult to test because real objects cannot be replaced with mock objects.

A factory is the location of a concrete class in the code at which objects are constructed. Implementation of the pattern intends to insulate the creation of objects from their usage and to create families of related objects without depending 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.

The pattern describes how to solve such problems:

  • Encapsulate object creation in a separate (factory) object by defining and implementing an interface for creating objects.
  • Delegate object creation to a factory object instead of creating objects directly.

This makes a class independent of how its objects are created. A class may be configured with a factory object, which it uses to create objects, and the factory object can be exchanged at runtime.

Definition

[edit]

Design Patterns describes the abstract factory pattern as "an interface for creating families of related or dependent objects without specifying their concrete classes."[4]

Usage

[edit]

The factory determines the concrete type of object to be created, and it is here that the object is actually created. However, the factory only returns a reference (in Java, for instance, by the new operator) or a pointer of an abstract type to the created concrete object.

This insulates client code from object creation by having clients request that a factory object create an object of the desired abstract type and return an abstract pointer to the object.[5]

An example is 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 such asFancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter() and createResume() that would create corresponding objects such asFancyLetter or ModernResume. Each of these products is derived from a simple abstract class such asLetter or Resume of which the client is aware. The client code would acquire 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. The client would only need to know how to handle the abstract Letter or Resume class, not the specific version that was created by the concrete factory.

As the factory only returns a reference or a pointer to an abstract type, the client code that requested the object from the factory is not aware of—and is not burdened by—the actual concrete type of the object that was created. However, the abstract factory knows the type of a concrete object (and hence a concrete factory). For instance, the factory may read the object's type from a configuration file. The client has no need to specify the type, as the type has already been specified in the configuration file. In particular, this means:

  • The client code has no knowledge of the concrete type, not needing to include any header files or class declarations related to it. 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 interfaces.[6]
  • Adding new concrete types is performed by modifying the client code to use a different factory, a modification that 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. Doing so would require changing every location in the code where a new object is created as well as ensuring that all such code locations have knowledge of the new concrete type, for example, by including a concrete class header file. If all factory objects are stored globally in a singleton object, and all client code passes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object.[6]

Structure

[edit]

UML diagram

[edit]
A sample UML class and sequence diagram for the abstract factory design pattern. [7]
A sample UML class and sequence diagram for the abstract factory design pattern. [7]

In the above UML class diagram, the Client class that requires ProductA and ProductB objects does not instantiate the ProductA1 and ProductB1 classes directly. Instead, the Client refers to the AbstractFactory interface for creating objects, which makes the Client independent of how the objects are created (which concrete classes are instantiated). The Factory1 class implements the AbstractFactory interface by instantiating the ProductA1 and ProductB1 classes.

The UML sequence diagram shows the runtime interactions. The Client object calls createProductA() on the Factory1 object, which creates and returns a ProductA1 object. Thereafter, the Client calls createProductB() on Factory1, which creates and returns a ProductB1 object.

Variants

[edit]

The original structure of the abstract factory pattern, as defined in 1994 in Design Patterns, is based on abstract classes for the abstract factory and the abstract products to be created. The concrete factories and products are classes that specialize the abstract classes using inheritance.[4]

A more recent structure of the pattern is based on interfaces that define the abstract factory and the abstract products to be created. This design uses native support for interfaces or protocols in mainstream programming languages to avoid inheritance. In this case, the concrete factories and products are classes that realize the interface by implementing it.[1]

Example

[edit]

This C++11 implementation is based on the pre C++98 implementation in the book.

#include <iostream>

enum Direction {North, South, East, West};

class MapSite {
public:
  virtual void enter() = 0;
  virtual ~MapSite() = default;
};

class Room : public MapSite {
public:
  Room() :roomNumber(0) {}
  Room(int n) :roomNumber(n) {}
  void setSide(Direction d, MapSite* ms) {
    std::cout << "Room::setSide " << d << ' ' << ms << '\n';
  }
  virtual void enter() {}
  Room(const Room&) = delete; // rule of three
  Room& operator=(const Room&) = delete;
private:
  int roomNumber;
};

class Wall : public MapSite {
public:
  Wall() {}
  virtual void enter() {}
};

class Door : public MapSite {
public:
  Door(Room* r1 = nullptr, Room* r2 = nullptr)
    :room1(r1), room2(r2) {}
  virtual void enter() {}
  Door(const Door&) = delete; // rule of three
  Door& operator=(const Door&) = delete;
private:
  Room* room1;
  Room* room2;
};

class Maze {
public:
  void addRoom(Room* r) {
    std::cout << "Maze::addRoom " << r << '\n';
  }
  Room* roomNo(int) const {
    return nullptr;
  }
};

class MazeFactory {
public:
  MazeFactory() = default;
  virtual ~MazeFactory() = default;

  virtual Maze* makeMaze() const {
    return new Maze;
  }
  virtual Wall* makeWall() const {
    return new Wall;
  }
  virtual Room* makeRoom(int n) const {
    return new Room(n);
  }
  virtual Door* makeDoor(Room* r1, Room* r2) const {
    return new Door(r1, r2);
  }
};

// If createMaze is passed an object as a parameter to use to create rooms, walls, and doors, then you can change the classes of rooms, walls, and doors by passing a different parameter. This is an example of the Abstract Factory (99) pattern.

class MazeGame {
public:
  Maze* createMaze(MazeFactory& factory) {
    Maze* aMaze = factory.makeMaze();
    Room* r1 = factory.makeRoom(1);
    Room* r2 = factory.makeRoom(2);
    Door* aDoor = factory.makeDoor(r1, r2);
    aMaze->addRoom(r1);
    aMaze->addRoom(r2);
    r1->setSide(North, factory.makeWall());
    r1->setSide(East, aDoor);
    r1->setSide(South, factory.makeWall());
    r1->setSide(West, factory.makeWall());
    r2->setSide(North, factory.makeWall());
    r2->setSide(East, factory.makeWall());
    r2->setSide(South, factory.makeWall());
    r2->setSide(West, aDoor);
    return aMaze;
  }
};

int main() {
  MazeGame game;
  MazeFactory factory;
  game.createMaze(factory);
}

The program output is:

Maze::addRoom 0x1317ed0
Maze::addRoom 0x1317ef0
Room::setSide 0 0x1318340
Room::setSide 2 0x1317f10
Room::setSide 1 0x1318360
Room::setSide 3 0x1318380
Room::setSide 0 0x13183a0
Room::setSide 2 0x13183c0
Room::setSide 1 0x13183e0
Room::setSide 3 0x1317f10

See also

[edit]

References

[edit]
  1. ^ a b c Freeman, Eric; Robson, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Hendrickson, Mike; Loukides, Mike (eds.). Head First Design Patterns (paperback). Vol. 1. O'REILLY. p. 156. ISBN 978-0-596-00712-6. Retrieved 2012-09-12.
  2. ^ a b Freeman, Eric; Robson, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Hendrickson, Mike; Loukides, Mike (eds.). Head First Design Patterns (paperback). Vol. 1. O'REILLY. p. 162. ISBN 978-0-596-00712-6. Retrieved 2012-09-12.
  3. ^ "The Abstract Factory design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-11.
  4. ^ a b Gamma, Erich; Richard Helm; Ralph Johnson; John M. Vlissides (2009-10-23). "Design Patterns: Abstract Factory". informIT. Archived from the original on 2012-05-16. 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.{{cite web}}: CS1 maint: bot: original URL status unknown (link)
  5. ^ Veeneman, David (2009-10-23). "Object Design for the Perplexed". The Code Project. Archived from the original on 2011-02-21. 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.{{cite web}}: CS1 maint: bot: original URL status unknown (link)
  6. ^ a b "Abstract Factory: Implementation". OODesign.com. Retrieved 2012-05-16.
  7. ^ "The Abstract Factory design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017-08-12.
[edit]