Javascript Static Singleton Pattern


/ Published in: JavaScript
Save to your folder(s)

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 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


Copy this code and paste it in your HTML
  1. var SingletonTester = (function () {
  2. // options: an object containing configuration options for the singleton
  3. // e.g var options = { name: 'test', pointX: 5};
  4. function Singleton(options) {
  5. // set options to the options supplied or an empty object if none provided.
  6. options = options || {};
  7. //set the name parameter
  8. this.name = 'SingletonTester';
  9. //set the value of pointX
  10. this.pointX = args.pointX || 6;
  11. //set the value of pointY
  12. this.pointY = args.pointY || 10; }
  13.  
  14. // this is our instance holder
  15. var instance;
  16.  
  17. // this is an emulation of static variables and methods
  18. var _static = {
  19. name: 'SingletonTester',
  20. // This is a method for getting an instance
  21. // It returns a singleton instance of a singleton object
  22. getInstance: function (options) {
  23. if (instance === undefined) {
  24. instance = new Singleton(options);
  25. }
  26. return instance;
  27. }
  28. };
  29. return _static;
  30. })();
  31.  
  32. var singletonTest = SingletonTester.getInstance({
  33. pointX: 5
  34. });
  35.  
  36. console.log(singletonTest.pointX); // outputs 5

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.