dev-resources.site
for different kinds of informations.
How to implement simple Factory Pattern in Node.js
https://grokonez.com/design-pattern/implement-simple-factory-method-pattern-node-js-example
How to implement simple Factory Pattern in Node.js
Instead of using class constructors or new
keyword to create an object of a class, we can abstract this process. So, we can determine the type of object at run-time, by the time of generating that class object. The implementation seems like Factory Method, but simpler than Factory Method. This simple Factory is not treated as a standard GoF design pattern, but the approach is common to any place where we want to separate the code that varies a lot from the code that does not vary.
In this tutorial, grokonez shows you how to do it in NodeJs.
Nodejs simple Factory Pattern example
Overview
In this example, we have 3 types of cars: Audi, BMW, Mercedes. The car generating process depends on the input string "Audi"
or "BMW"
or "Mercedes"
.
CarFactory
is the Factory class. In the client, we won't use new
keyword but create()
method to create a new car:
const BMW = CarFactory.create('BMW');
Sample Structure
Implement simple Factory Pattern in Nodejs
Create default class
This Car
class is a parent class for Audi
, BMW
, Mercedes
class that we're gonna create in the next steps.
default_car.js
class Car {
constructor(name) {
this.name = name + '-' + Math.random().toString(36).substring(2, 15);
}
showInfo() {
console.log(`I'm ${this.name}`)
}
}
module.exports = Car;
This class has constructor method that assign a generated id to the car's name and a showInfo()
method to show the name
field.
Create subclasses of default class
Now we create 3 classes: Audi
, BMW
, Mercedes
that extends default Car
class above.
More at:
https://grokonez.com/design-pattern/implement-simple-factory-method-pattern-node-js-example
How to implement simple Factory Pattern in Node.js
Featured ones: