Posted By

nerdfiles on 01/17/10


Tagged

javascript oop pattern module


Versions (?)

Simple Singleton Pattern Example & Facade Pattern Example


 / Published in: JavaScript
 

URL: http://blog.reindel.com/2008/12/22/the-facade-design-pattern-in-javascript/

For private variables, private methods; closed API.

  1. var modulePatternTest = (function() {
  2.  
  3. var array = [];
  4.  
  5. return {
  6. addToArray: function() {
  7. array.push(1,2,3,4);
  8. },
  9. removeFromArray: function() {
  10. array.pop();
  11. },
  12. alertArray: function() {
  13. alert(array.length);
  14. }
  15. }
  16.  
  17. })();
  18.  
  19. modulePatternTest.addToArray();
  20. modulePatternTest.alertArray();
  21.  
  22. /*----------------- Facade Pattern ------------------*/
  23. var DBUG = function() {
  24. _private = {
  25. getThis : function( count ) {
  26. /* ... implementation ... */
  27. },
  28. putThis : function() {
  29. /* ... implementation ... */
  30. },
  31. runThis : function() {
  32. /* ... implementation ... */
  33. }
  34. };
  35. return {
  36. facade : function( args ) {
  37. _private.getThis( args.count );
  38. _private.putThis();
  39. if ( args.runIt ) {
  40. _private.runThis();
  41. }
  42. }
  43. }
  44. }();
  45.  
  46. window.onload = function() {
  47. DBUG.facade({
  48. runIt : true,
  49. count : 1
  50. });
  51. DBUG.facade({
  52. runIt : false,
  53. count : 2
  54. });
  55. }
  56.  
  57. module = (function() {
  58. _privateVar = "cow";
  59.  
  60. function getter() {
  61. return _privateVar;
  62. }
  63.  
  64. function setter(val) {
  65. if (!val) _privateVar = _privateVar;
  66. else _privateVar = val;
  67. }
  68.  
  69. return {
  70. public_getter: getter,
  71. public_setter: setter
  72. }
  73. })();
  74. module.public_setter('cannibalism');
  75. console.log( module.public_getter() );

Report this snippet  

You need to login to post a comment.