Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Abstract factory pattern

From Wikipedia, the free encyclopedia
(Redirected fromAbstract factory)
Software design pattern
UML class diagram

Theabstract factory pattern insoftware 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 individualfactories 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 genericinterface of the factory to create the concreteobjects that are part of the family. Theclient 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] Thispattern 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 atruntime. However, employment of this pattern, as with similardesign 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 1994Design 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 whichobjects 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 newderived types to be introduced with no change to the code that uses thebase 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 thenewoperator) or apointer of an abstract type to the created concrete object.

This insulates client code fromobject creation by having clients request that afactory object create an object of the desiredabstract type and return an abstract pointer to the object.[5]

An example is an abstract factory classDocumentCreator that provides interfaces to create a number of products (e.g.,createLetter() andcreateResume()). The system would have any number of derived concrete versions of theDocumentCreator class such asFancyDocumentCreator orModernDocumentCreator, each with a different implementation ofcreateLetter() andcreateResume() that would create corresponding objects such asFancyLetter orModernResume. Each of these products is derived from a simpleabstract class such asLetter orResume of which the client is aware. The client code would acquire an appropriateinstance of theDocumentCreator and call itsfactory methods. Each of the resulting objects would be created from the sameDocumentCreator implementation and would share a common theme. The client would only need to know how to handle the abstractLetter orResume 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 concretetype, not needing to include anyheader files orclassdeclarations 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 theirabstract 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 thesame 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 asingleton 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 aboveUMLclass diagram, theClient class that requiresProductA andProductB objects does not instantiate theProductA1 andProductB1 classes directly. Instead, theClient refers to theAbstractFactory interface for creating objects, which makes theClient independent of how the objects are created (which concrete classes are instantiated). TheFactory1 class implements theAbstractFactory interface by instantiating theProductA1 andProductB1 classes.

TheUMLsequence diagram shows the runtime interactions. TheClient object callscreateProductA() on theFactory1 object, which creates and returns aProductA1 object. Thereafter, theClient callscreateProductB() onFactory1, which creates and returns aProductB1 object.

Variants

[edit]

The original structure of the abstract factory pattern, as defined in 1994 inDesign 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]

ThisC++23 implementation is based on the pre-C++98 implementation in the book.

importstd;enumclassDirection{North,South,East,West};classMapSite{public:virtualvoidenter()=0;virtual~MapSite()=default;};classRoom:publicMapSite{public:Room():roomNumber(0){}Room(intn):roomNumber(n){}voidsetSide(Directiond,MapSite*ms){std::println("Room::setSide {} ms",d);}virtualvoidenter(){}Room(constRoom&)=delete;// rule of threeRoom&operator=(constRoom&)=delete;private:introomNumber;};classWall:publicMapSite{public:Wall(){}virtualvoidenter(){}};classDoor:publicMapSite{public:Door(Room*r1=nullptr,Room*r2=nullptr):room1(r1),room2(r2){}virtualvoidenter(){}Door(constDoor&)=delete;// rule of threeDoor&operator=(constDoor&)=delete;private:Room*room1;Room*room2;};classMaze{public:voidaddRoom(Room*r){std::println("Maze::addRoom {}",r);}Room*roomNo(int)const{returnnullptr;}};classMazeFactory{public:MazeFactory()=default;virtual~MazeFactory()=default;virtualMaze*makeMaze()const{returnnewMaze;}virtualWall*makeWall()const{returnnewWall;}virtualRoom*makeRoom(intn)const{returnnewRoom(n);}virtualDoor*makeDoor(Room*r1,Room*r2)const{returnnewDoor(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.classMazeGame{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(Direction::North,factory.makeWall());r1->setSide(Direction::East,aDoor);r1->setSide(Direction::South,factory.makeWall());r1->setSide(Direction::West,factory.makeWall());r2->setSide(Direction::North,factory.makeWall());r2->setSide(Direction::East,factory.makeWall());r2->setSide(Direction::South,factory.makeWall());r2->setSide(Direction::West,aDoor);returnaMaze;}};intmain(){MazeGamegame;MazeFactoryfactory;game.createMaze(factory);}

The program output is:

Maze::addRoom 0x1317ed0Maze::addRoom 0x1317ef0Room::setSide 0 0x1318340Room::setSide 2 0x1317f10Room::setSide 1 0x1318360Room::setSide 3 0x1318380Room::setSide 0 0x13183a0Room::setSide 2 0x13183c0Room::setSide 1 0x13183e0Room::setSide 3 0x1317f10

See also

[edit]

References

[edit]
  1. ^abcFreeman, 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. Retrieved2012-09-12.
  2. ^abFreeman, 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. Retrieved2012-09-12.
  3. ^"The Abstract Factory design pattern - Problem, Solution, and Applicability".w3sDesign.com. Retrieved2017-08-11.
  4. ^abGamma, Erich; Richard Helm; Ralph Johnson; John M. Vlissides (2009-10-23)."Design Patterns: Abstract Factory". informIT. Archived from the original on 2012-05-16. Retrieved2012-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. Retrieved2012-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. ^ab"Abstract Factory: Implementation". OODesign.com. Retrieved2012-05-16.
  7. ^"The Abstract Factory design pattern - Structure and Collaboration".w3sDesign.com. Retrieved2017-08-12.

External links

[edit]
The WikibookComputer Science Design Patterns has a page on the topic of:Abstract Factory in action
Gang of Four
patterns
Creational
Structural
Behavioral
Concurrency
patterns
Architectural
patterns
Other
patterns
Books
People
Communities
See also
Retrieved from "https://en.wikipedia.org/w/index.php?title=Abstract_factory_pattern&oldid=1265430540"
Category:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp