Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Abstract Factory Design Pattern
Subhrodip Mohanta
Subhrodip Mohanta

Posted on

     

Abstract Factory Design Pattern

This is aCreational Design Pattern underGang of Four

Also known as

Kit

Intent

Provide an interface for creating families of related or dependent
objects without specifying their concrete classes.

Explanation

Real world example

To create a kingdom we need objects with a common theme. Elven kingdom needs an Elven king, Elven castle and Elven army whereas Orcish kingdom needs an Orcish king, Orcish castle and Orcish army. There is a dependency between the objects in the kingdom.

In plain words

A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.

Wikipedia says

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes

Programmatic Example

Translating the kingdom example above. First of all we have some interfaces and implementation for the objects in the
kingdom.

publicinterfaceCastle{StringgetDescription();}publicinterfaceKing{StringgetDescription();}publicinterfaceArmy{StringgetDescription();}// Elven implementations ->publicclassElfCastleimplementsCastle{staticfinalStringDESCRIPTION="This is the Elven castle!";@OverridepublicStringgetDescription(){returnDESCRIPTION;}}publicclassElfKingimplementsKing{staticfinalStringDESCRIPTION="This is the Elven king!";@OverridepublicStringgetDescription(){returnDESCRIPTION;}}publicclassElfArmyimplementsArmy{staticfinalStringDESCRIPTION="This is the Elven Army!";@OverridepublicStringgetDescription(){returnDESCRIPTION;}}// Orcish implementations similarly -> ...
Enter fullscreen modeExit fullscreen mode

Then we have the abstraction and implementations for the kingdom factory

publicinterfaceKingdomFactory{CastlecreateCastle();KingcreateKing();ArmycreateArmy();}publicclassElfKingdomFactoryimplementsKingdomFactory{publicCastlecreateCastle(){returnnewElfCastle();}publicKingcreateKing(){returnnewElfKing();}publicArmycreateArmy(){returnnewElfArmy();}}publicclassOrcKingdomFactoryimplementsKingdomFactory{publicCastlecreateCastle(){returnnewOrcCastle();}publicKingcreateKing(){returnnewOrcKing();}publicArmycreateArmy(){returnnewOrcArmy();}}
Enter fullscreen modeExit fullscreen mode

Now we have our abstract factory that lets us make family of related objects i.e. Elven kingdom factory creates Elven castle, king and army etc.

varfactory=newElfKingdomFactory();varcastle=factory.createCastle();varking=factory.createKing();vararmy=factory.createArmy();castle.getDescription();king.getDescription();army.getDescription();
Enter fullscreen modeExit fullscreen mode

Program output:

ThisistheElvencastle!ThisistheElvenking!ThisistheElvenArmy!
Enter fullscreen modeExit fullscreen mode

Now, we can design a factory for our different kingdom factories. In this example, we created FactoryMaker, responsible for returning an instance of either ElfKingdomFactory or OrcKingdomFactory.

The client can use FactoryMaker to create the desired concrete factory which, in turn, will produce different concrete objects (Army, King, Castle).

In this example, we also used an enum to parameterize which type of kingdom factory the client will ask for.

publicstaticclassFactoryMaker{publicenumKingdomType{ELF,ORC}publicstaticKingdomFactorymakeFactory(KingdomTypetype){switch(type){caseELF:returnnewElfKingdomFactory();caseORC:returnnewOrcKingdomFactory();default:thrownewIllegalArgumentException("KingdomType not supported.");}}}publicstaticvoidmain(String[]args){varapp=newApp();LOGGER.info("Elf Kingdom");app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF));LOGGER.info(app.getArmy().getDescription());LOGGER.info(app.getCastle().getDescription());LOGGER.info(app.getKing().getDescription());LOGGER.info("Orc Kingdom");app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC));--similaruseoftheorcfactory}
Enter fullscreen modeExit fullscreen mode

Class diagram

alt text

Applicability

Use the Abstract Factory pattern when

  • The system should be independent of how its products are created, composed and represented
  • The system should be configured with one of multiple families of products
  • The family of related product objects is designed to be used together, and you need to enforce this constraint
  • You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations
  • The lifetime of the dependency is conceptually shorter than the lifetime of the consumer.
  • You need a run-time value to construct a particular dependency
  • You want to decide which product to call from a family at runtime.
  • You need to supply one or more parameters only known at run-time before you can resolve a dependency.
  • When you need consistency among products
  • You don’t want to change existing code when adding new products or families of products to the program.

Example use cases

  • Selecting to call to the appropriate implementation of FileSystemAcmeService or DatabaseAcmeService or NetworkAcmeService at runtime.
  • Unit test case writing becomes much easier
  • UI tools for different OS

Consequences:

  • Dependency injection in java hides the service class dependencies that can lead to runtime errors that would have been caught at compile time.
  • While the pattern is great when creating predefined objects, adding the new ones might be challenging.
  • The code becomes more complicated than it should be, since a lot of new interfaces and classes are introduced along with the pattern.

Tutorial

Known uses

Related patterns

Credits


Code can be foundhere

Find out about more design patterns fromhere

Credit to Original Authors of this post:

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Writing readable and scalable code that unites distributed systems to power your daily apps
  • Location
    Kolkata, India
  • Education
    Computer Science Engineer
  • Work
    Java Developer at Wipro
  • Joined

More fromSubhrodip Mohanta

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp