DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Design Patterns - Creational - Factory

Image description

Factory pattern creates new objects delegating which class to instantiate in subclasses.

In the below example, MovieFactory decides what kind of Movie to create.

class MovieFactory {
  create(genre) {
    if (genre === 'Adventure') {
        return new Movie(genre, 10000);
    }

    if (genre === 'Action') {
        return new Movie(genre, 20000);
    }
  }
}

class Movie {
  constructor(type, price) {
    this.type = type;
    this.price = price;
  }
}

export default MovieFactory;
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Use this pattern when you want a subclass to decide what object to create.

๐Ÿš€ Pros:

โž– We avoid tight coupling between the creator and the concrete products.

โž– Single Responsibility Principle. We can move the product creation code into one place in the program, making the code easier to support.

โž– Open/Closed Principle. We can introduce new types of products into the program without breaking existing client code.

โ›” Cons:

โž– The code may become more complicated since We need to introduce a lot of new subclasses to implement the pattern. The best-case scenario is when weโ€™re introducing the pattern into an existing hierarchy of creator classes.


I hope you found it useful. Thanks for reading. ๐Ÿ™

Let's get connected! You can find me on:

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, weโ€™ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay