University of Cincinnati logo and link  
CinJUG: Design Patterns, October 16, 2006
 
 

Abstract Factory Pattern

UC ingot

Intent: “Provide an interface for creating families of related or dependent objects without specifying their concrete classes” -GoF

  • Create an abstract factory class, and abstract classes for each of the widgets. The concrete factory instantiates the appropriate concrete widgets.

  • Enforces dependencies between factory and classes.

Applicability

  • System should be independent of how objects are created, composed, represented.

  • System should be configured with one of multiple families of objects.

  • 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.

Participants

  • Abstract Factory

  • Concrete Factory

    • Consolidate these two into one: MonthlyFactory.

  • Abstract Product

    • MonthlyCommand interface.

  • Concrete Product

    • MonthlyCommand implementation.

  • Client

    • Runner.

Collaborations

  • Typically, one instance of Concrete Factory is created at runtime, often with the Singleton factory.

  • You can switch factories to get different products.

  • The AbstractFactory can defer creation of product objects to ConcreteFactory subclasses.

Consequences

  • Isolates concrete classes. Concrete class names do not appear in the client code, because they are isolated in the implementation of the concrete factory.

  • Makes exchanging product families easy. The class of a concrete factory appears only where it is instantiated. The entire product family changes at once, and in one place.

  • It promotes consistency among products

  • Supporting new products isn't easy (except in my implementation, which instantiates objects dynamically).

Implementation

  • AbstractFactory only defines interface for creating object. Concrete factory actually creates them.

  • Define extensible factories.

    • Single “make” method with a parameter defining which type of object to make.

    • But, all objects created must have the same abstract interface type. Thus, cannot perform subclass specific operations, unless downcast.


Example

  • User Interfaces

  • Different cars, same company (Ford, Mercury, Mazda)

  Factory Method Implementation of Abstract Factory

 Cincinnati Java Users Group