Skip to content

Latest commit

 

History

History
60 lines (42 loc) · 3.36 KB

File metadata and controls

60 lines (42 loc) · 3.36 KB

Also know as Kit.

Intend

Provide an interface for the creation of families of related objects without specifying their concrete classes.

You should use this pattern in the following cases :

  • The system should be independant of how its products are created, composed and represented.
  • The system might be configured with multiple product families.
  • When you need to enforce the fact that a family of products should be used together.
  • You want to provide a library class of products but only reveal the interface (hide the implementation).

How it's done

UML

Participants

  • AbstractFactory : Interface for operations that create AbstractProduct objects.
  • ConcreteFactory : Implement AbstractFactory interface to produce ConcreteProduct objects.
  • AbstractProduct : Interface for a type of product.
  • ConcreteProduct :
    • Implement AbstractProduct interface.
    • Defines a product object to be created by the corresponding ConcreteFactory.
  • Client : Only uses the interfaces declared by AbstractFactory and AbstractProduct.

How to implement

You should implement the Abstract factory pattern following these steps :

  1. Define a matrix of your products families (products families * products type)
  2. Declare an abstract interface (AbstractProduct) for every product types. All the ConcreteProduct classes have to implement these interfaces.
  3. Declare an abstract factory interface (AbstractInterface) with the required methods to create every abstract product.
  4. Implement the corresponding concrete factory classes (ConcreteFactory) for each product variant. They will create the Products with the help of ConcreteProduct.
  5. Initialize the factories and make it accessible to every classes that construct the products (Client).

NB : You can implement the factories as Singleton. Indeed, your application will likely need only one instance of ConcreteFactory per product family.

Note : UML class diagram taken from here

Pros & cons

Pros

  • Compatibility : All the products created via a Factory are compatible with eatch other.
  • Coupling : Avoid tight coupling between ConcreteProduct and client code.
  • Maintainability : The product creation takes place in a single, well-identified, place. It makes the code easier to maintain.
  • Flexible : It is easy to introduce new product families without breaking the Client code.

Cons

  • Complexity : The code might become more complicated than it should be with the multiplication of interfaces and classes.

Notes

As you can see in the How to implement section, the Abstract factory pattern are often implemented using the Factory method pattern.

The ConcreteFactory are also often implemented as Singleton.

Here are some usefull ressources :