Factory and Singleton Pattern in JavaScript
August 26, 2021 · 2 min readLucian CiobanuThe factory pattern aims to simplify object creation and I've found online an interesting example which requires the repositories and keeps them in a object. The implementation is as follows:
var repoFactory = function() {
var repos = this;
var repoList = [{name: 'task', source: './taskRepository'},
{name: 'user', source: './userRepository'},
{name: 'project', source: './projectRepository'}];
repoList.forEach(function(repo) {
repos[repo.name] = require(repo.source)()
});
}
module.exports = new repoFactory;
While the singleton pattern is used to restrict an object to one instance across the app. This patterns remembers the last time we used it and it's going to return the same instacne back:
var TaskRepo = (function() {
var taskRepo;
function createRepo() {
var taskRepo = new Object("Task");
return taskRepo;
}
return {
getInstance: function() {
if(!taskRepo) {
taskRepo = createRepo();
}
return taskRepo;
}
};
})();
//test the singleton
var repo1 = TaskRepo.getInstance();
var repo2 = TaskRepo.getInstance();
if(repo1 === repo2) {
console.log("Same TaskRepo");
}
One example of singleton is that all the services in Angular are created with this desing pattern.
Hope this helped!
Cheers,
Lucian

Web Development & Software Delivery