GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — js_designpatterns/proxy.js at master · m1oto/js_designpatterns Expand file tree/ Copy pathproxy.jsMore file actions 100 lines (95 loc) · 2.16 KB / Copy pathproxy.jsFile metadata and controls100 lines (95 loc) · 2.16 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 // You should use proxy pattern when you want to extend a // class functionality without changing its implementation /**************** Original Class ****************/ function Hotel(stars, isCityCenter, isNew, numberOfRooms, avgRoomSize) { this.stars = stars; this.isCityCenter = isCityCenter; this.isNew = isNew; this.numberOfRooms = numberOfRooms; this.avgRoomSize = avgRoomSize; } Hotel.prototype = { // Define getters and setters getStars: function() { return this.stars; }, setStars: function(starsRate) { this.stars = starsRate; }, isCityCenter: function() { return this.isCityCenter; }, toggleCenter: function() { this.isCityCenter = !this.isCityCenter; }, isNew: function() { return this.isNew; }, toggleNew: function() { this.isNew = !this.isNew; }, getNumberOfRooms: function() { return this.numberOfRooms; }, setNumberOfRooms: function(num) { this.numberOfRooms = num; }, getAvgRoomSize: function() { return this.avgRoomSize; }, setAvgRoomSize: function(newAvg) { this.avgRoomSize = newAvg; } } /**************** Proxy ****************/ var HotelProxy = function(stars, isCityCenter, isNew, numberOfRooms, avgRoomSize) { // Create Hotel Instance var hotel = new Hotel(stars, isCityCenter, isNew, numberOfRooms, avgRoomSize); // Private function function scoreByStars(stars) { switch(stars) { case(5): return 6; case(4): return 5; case(3): return 3; case(2): return 1.5; default: return 0.5; } } // Extend hotel instance Object.assign(hotel, { getScore: function() { var score = scoreByStars(hotel.stars); if(hotel.isCityCenter) { score += 2; } if(hotel.isNew) { score += 1.5; } if(hotel.numberOfRooms > 5000) { score += 0.5; } return score; }, getHotelRoomsVolume: function() { return hotel.numberOfRooms * hotel.avgRoomSize; } }); // Return extended instance return hotel; } // Usage example var hp = HotelProxy(4, true, false, 2800, 150); console.log(hp.getScore()); // 7 console.log(hp.getHotelRoomsVolume()); // 420000 hp.setAvgRoomSize(160); console.log(hp.getHotelRoomsVolume()); // 448000 hp.setStars(5); console.log(hp.getScore()); //8 |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |