Guest User

Untitled

a guest
Jan 18th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>The factory pattern</title>
  7. </head>
  8. <body>
  9.  
  10. <script id="jsbin-javascript">
  11. /*A common implementation of this pattern is usually using
  12. a class or static method of a class.
  13. The purposes of such a class or method are as follows:
  14. - It abstracts out repetitive operations when creating
  15. similar objects
  16. - It allows the consumers of the factory to create
  17. objects without knowing the internals of the object creation
  18. */
  19.  
  20. //Car Factory Constructor
  21. function CarFactory() {};
  22. CarFactory.prototype.info = function() {
  23. console.log('This car has ' + this.doors + 'doors and a ' + this.engine_capacity + 'liter engine');
  24. };
  25.  
  26. // The static Factory Method
  27. CarFactory.make = function (type) {
  28. var constr = type, car;
  29. CarFactory[constr].prototype = new CarFactory();
  30.  
  31. // Create a new instance
  32. car = new CarFactory[constr]();
  33. return car;
  34.  
  35. };
  36.  
  37. CarFactory.Compact = function () {
  38. this.doors = 4;
  39. this.engine_capacity = 2;
  40. }
  41.  
  42. var golf = CarFactory.make('Compact');
  43. console.log(golf);
  44.  
  45. </script>
  46.  
  47.  
  48.  
  49. <script id="jsbin-source-javascript" type="text/javascript">/*A common implementation of this pattern is usually using
  50. a class or static method of a class.
  51. The purposes of such a class or method are as follows:
  52. - It abstracts out repetitive operations when creating
  53. similar objects
  54. - It allows the consumers of the factory to create
  55. objects without knowing the internals of the object creation
  56. */
  57.  
  58. //Car Factory Constructor
  59. function CarFactory() {};
  60. CarFactory.prototype.info = function() {
  61. console.log('This car has ' + this.doors + 'doors and a ' + this.engine_capacity + 'liter engine');
  62. };
  63.  
  64. // The static Factory Method
  65. CarFactory.make = function (type) {
  66. var constr = type, car;
  67. CarFactory[constr].prototype = new CarFactory();
  68.  
  69. // Create a new instance
  70. car = new CarFactory[constr]();
  71. return car;
  72.  
  73. };
  74.  
  75. CarFactory.Compact = function () {
  76. this.doors = 4;
  77. this.engine_capacity = 2;
  78. }
  79.  
  80. var golf = CarFactory.make('Compact');
  81. console.log(golf);
  82. </script></body>
  83. </html>
Add Comment
Please, Sign In to add comment