Navratri Sale: Get Upto 30% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now

Creational Design Pattern: Factory Method Pattern

Level : Intermediate
Mentor: Shailendra Chauhan
Duration : 00:01:00

Factory Method pattern

The Factory pattern creates an item without exposing the creation logic. In this approach, an interface is used to create an object, but the subclass determines which class to instantiate.

Examples of Factory Methods

Need to create different logger types like:

  • Console Logger
  • Database Logger
  • File Logger etc.

Need to create different report types like:

  • PDF
  • Word etc.

Factory method pattern with UML diagram

The UML class diagram above defines the following classes, interfaces, and objects:

  • Product: This is the interface for creating objects.
  • ConcreteProduct: This class implements the Product interface.
  • Creator: This abstract class declares a factory method that yields a Product object.
  • ConcreteCreator: This class extends the Creator class by overriding the factory method, which returns a ConcreteProduct object.

When should you use the Factory Method Pattern?

The factory pattern is useful in the following situations:

  • Subclasses determine which objects should be produced.
  • The parent class enables for later instantiation of subclasses, which implies that an object is created only when it is needed.
  • The process of object creation must be centralized within the application.
  • A class (creator) will not be aware of which classes it must build.
Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this