Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width">
- <title>The factory pattern</title>
- </head>
- <body>
- <script id="jsbin-javascript">
- /*A common implementation of this pattern is usually using
- a class or static method of a class.
- The purposes of such a class or method are as follows:
- - It abstracts out repetitive operations when creating
- similar objects
- - It allows the consumers of the factory to create
- objects without knowing the internals of the object creation
- */
- //Car Factory Constructor
- function CarFactory() {};
- CarFactory.prototype.info = function() {
- console.log('This car has ' + this.doors + 'doors and a ' + this.engine_capacity + 'liter engine');
- };
- // The static Factory Method
- CarFactory.make = function (type) {
- var constr = type, car;
- CarFactory[constr].prototype = new CarFactory();
- // Create a new instance
- car = new CarFactory[constr]();
- return car;
- };
- CarFactory.Compact = function () {
- this.doors = 4;
- this.engine_capacity = 2;
- }
- var golf = CarFactory.make('Compact');
- console.log(golf);
- </script>
- <script id="jsbin-source-javascript" type="text/javascript">/*A common implementation of this pattern is usually using
- a class or static method of a class.
- The purposes of such a class or method are as follows:
- - It abstracts out repetitive operations when creating
- similar objects
- - It allows the consumers of the factory to create
- objects without knowing the internals of the object creation
- */
- //Car Factory Constructor
- function CarFactory() {};
- CarFactory.prototype.info = function() {
- console.log('This car has ' + this.doors + 'doors and a ' + this.engine_capacity + 'liter engine');
- };
- // The static Factory Method
- CarFactory.make = function (type) {
- var constr = type, car;
- CarFactory[constr].prototype = new CarFactory();
- // Create a new instance
- car = new CarFactory[constr]();
- return car;
- };
- CarFactory.Compact = function () {
- this.doors = 4;
- this.engine_capacity = 2;
- }
- var golf = CarFactory.make('Compact');
- console.log(golf);
- </script></body>
- </html>
Add Comment
Please, Sign In to add comment