Factory Method

Type : Creational design pattern

Intent

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

Applicability

Use the Abstract Factory pattern when

  • a system should be independent of how its products are created, composed, and represented.
  • a system should be configured with one of multiple families of products.
  • a 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.

Structure

Firstly, Abstract Factory pattern suggests is to explicitly declare interfaces for each distinct product of the product family

Abstract Factory pattern

Then we should declare the Abstract Factory which is an interface with list of creation methods for all products  that are part of the product family.

Abstract Factory pattern

Outcome

  • It isolates concrete classes. The Abstract Factory pattern helps you control the classes of objects that an application creates. Because a factory encapsulates the responsibility and the process of creating product objects, it isolates clients from implementation classes.
  • It makes exchanging product families easy. The class of a concrete factory appears only once in an application—that is, where it’s instantiated. This makes it easy to change the concrete factory an application uses. It can use different product configurations simply by changing the concrete factory.
  • It promotes consistency among products. When product objects in a family are designed to work together, it’s important that an application use objects from only one family at a time.
  • Supporting new kinds of products is difficult. Extending abstract factories to produce new kinds of Products isn’t easy. That’s because the AbstractFactory interface fixes the set of products that can be created.

Example Code