Posted By

timsommer on 07/30/12


Tagged

pattern Singleton design


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

burnandbass


Javascript Singleton Pattern


 / Published in: JavaScript
 

In conventional software engineering, the singleton pattern can be implemented by creating a class with a method that creates a new instance of the class if one doesn't exist. In the event of an instance already existing, it simply returns a reference to that object.

  1. var Singleton = (function () {
  2. var instantiated;
  3. function init() {
  4. // singleton here
  5. return {
  6. publicMethod: function () {
  7. console.log('hello world');
  8. },
  9. publicProperty: 'test'
  10. };
  11. }
  12. return {
  13. getInstance: function () {
  14. if (!instantiated) {
  15. instantiated = init();
  16. }
  17. return instantiated;
  18. }
  19. };
  20. })();
  21.  
  22. // calling public methods is then as easy as:
  23. Singleton.getInstance().publicMethod();

Report this snippet  

You need to login to post a comment.