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;
๐ 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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Top comments (0)