dev-resources.site
for different kinds of informations.
Javascript Factory Design Pattern
Published at
3/20/2023
Categories
javascript
designpatterns
factory
programming
Author
Bvnkumar
Design patterns are templates or solutions for common software development problems.
Design patterns are divided into three categories.
- Behavioral
- Creational
- Structural
The factory pattern is a creational design pattern that provides a generic interface for creating objects.
EX:-
function Developer(name , experience) {
this.name = name;
this.type = "Developer";
this.experience = experience;
}
function Tester(name, experience) {
this.name = name;
this.type = "Tester";
this.experience = experience;
}
function EmployeeFactory() {
this.create = (name, type) => {
switch (type) {
case 1:
return new Developer(name,4);
break;
case 2:
return new Tester(name,6);
break;
}
}
}
function say() {
console.log("i am " + this.name + " i am a " + this.type +" and having a "+ this.experience +"years of experience ");
}
let employees = [];
const employeeFactory = new EmployeeFactory();
employees.push(employeeFactory.create("Sam", 1));
employees.forEach((employee) => {
say.call(employee);
});
As you can see, we have created developer and Tester objects with their names. Using this pattern you could create as many objects you require each with their own name and experience.
Articles
12 articles in total
LRU (Least Recently Used) Cache Data Structure
read article
Observer Design Pattern using Javascript
read article
Javascript Factory Design Pattern
currently reading
Longest string without repeating characters in javaascript
read article
Print left view of binary tree
read article
Binary search algorithm implementation in JavaScript
read article
Javascript Binary heap data structure
read article
Javascript Linked List data structure
read article
Javascript Binary Tree data structure
read article
Javascript Queue data structure
read article
Javascript Set data structure
read article
Javascript Stack Data Structure.
read article
Featured ones: