Created
November 6, 2017 10:53
-
-
Save YoneMoreno/c66f764c723422664e87514dc55d647c to your computer and use it in GitHub Desktop.
Creating a singleton both in plain JS and using node commonJS cache behavior https://app.pluralsight.com/player?course=javascript-practical-design-patterns&author=jonathan-mills&name=javascript-practical-design-patterns-m3&clip=14&mode=live
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var taskHandler = require('./taskHandler'); | |
var myrepo = require('./Repo'); | |
myrepo.save('fromMain'); | |
myrepo.save('fromMain'); | |
myrepo.save('fromMain'); | |
taskHandler.save(); | |
taskHandler.save(); | |
taskHandler.save(); | |
taskHandler.save(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var repo = function(){ | |
var called = 0; | |
var save = function (task){ | |
called++; | |
console.log('Saving ' + task + | |
' Called ' + called + ' times'); | |
} | |
console.log('newing up task repo'); | |
return { | |
save: save | |
} | |
} | |
//Using repo() or new repo makes Node use the cache behavior to create a new repository only if it doesn't exist | |
module.exports = repo(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var TaskRepo = (function () { | |
var taskRepo; | |
function createRepo() { | |
var taskRepo = new Object("Task"); | |
return taskRepo; | |
} | |
return { | |
getInstance: function () { | |
if (!taskRepo) { | |
taskRepo = createRepo(); | |
} | |
return taskRepo; | |
} | |
}; | |
})(); | |
var repo1 = TaskRepo.getInstance(); | |
var repo2 = TaskRepo.getInstance(); | |
if(repo1 === repo2){ | |
console.log("Same TaskRepo") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var myrepo = require('./Repo'); | |
var taskHandler = function () { | |
return { | |
save: function (){ | |
myrepo.save('Hi from taskHandler'); | |
} | |
} | |
} | |
module.exports = taskHandler(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment