Docsity

Factory Method Design Pattern, Study notes of Design

Partial preview of the text

Download Factory Method Design Pattern and more Study notes Design in PDF only on Docsity!

Factory Method

By: Kirin Masood

Overview

Significance:

Use the factory pattern...

When you don’t know what class object you need ahead of time

When all of the potential classes are in the same subclass hierarchy

To centralize class selection code

When you don’t want the user to know every subclass

To encapsulate object creation

Significance: Solution

Solution:

  • Factory Method!
  • Classes can defer instantiation to subclasses at runtime

Main idea: Factory creates the new object

Building the Diagram Definition of the

Factory Method

Factory Method: Interface

Product: This is the interface of the objects the factory method creates

Ex: Dog Factory

Product: Dog

Method that must be implemented via the interface: speak();

Factory Method: Concrete Creator

Provides an interface for the creation of Products

Ex: Dog Factory Product: Dog Concrete Product: Poodle, Dalmation, Beagle Method that must be implemented: speak(); Concrete Creator: DogFactory that returns the Dog when the function is called i.e. Return new Poodle();

Factory Method: Creator

Declares the factory method which returns an object of type Product.

Product: Dog Concrete Product: Poodle, Dalmation, Beagle Method that must be implemented: speak(); Concrete Creator: DogFactory Creator: Gets different dogs from the factory

Factory Method: Behavior

  • Client makes a call to the creator
  • creator uses the factory method
  • Factory method gets a new instance of concrete product
  • It then completes the anOperation() on the concrete product
  • Completes

Advantages of using the Factory Method

Factory Method Example

Example: UML

Interface: Color with method draw

Concrete Classes: Red, Blue, Green Implementing the same interface

Concrete Creator: ColorFactory

Creator: FactoryPatternDemo

Red Blue Green

Color

ColorFactory

+getColor():Color

Product: Interface

Example: UML

Interface: Color

Red Blue Green

Color

ColorFactory

+getColor():Color