DEV Community

Coder
Coder

Posted on • Originally published at itscoderslife.wordpress.com on

1

Factory Design pattern [Creational]

The factory method pattern allows callers to create instances of objects by only knowing the protocol or the top level base class and not the exact implementation classes.

  • Callers will never know any details about the implementation classes.
  • The factory method incorporates the logic required to decide which implementation class to instantiate based on the criteria supplied by the caller.
  • Callers must not know all the implementation classes, just the protocol or the base class.
  • Depending components must only know about the protocol or the base class and the class exposing the factory method.
  • This pattern allows changing the existing implementation classes or adding new ones without exposing these details to the components that rely on them.
  • Factory Method: creation through inheritance. Prototype: creation through delegation.

The factory method selects the implementation class to instantiate based on the criteria supplied by the caller. The caller must know only a single type.

Example: Color Palette – User needs to mention the name of the palette and all colors with respect to that set will be populated and ready.

Color Palette – User needs to mention the name of the palette and all colors with respect to that set will be populated and ready.

Summary : The factory method pattern is a good choice if we want to prevent exposing all implementation classes to our callers.

_Note that the factory method design pattern cannot be applied when there is no common protocol or shared base class. _

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay