小谈Javascript设计模式
- 5. Factory-EXPif (typeofXMLHttpRequest != "undefined") { return new XMLHttpRequest();} else if (typeofwindow.ActiveXObject != "undefined") { return new ActiveXObject("MSXML2.XMLHttp");}function XMLHttpFactory() {}XMLHttpFactory.createXMLHttp = function () { if (typeofXMLHttpRequest != "undefined") { return new XMLHttpRequest(); } else if (typeofwindow.ActiveXObject != "undefined") { return new ActiveXObject("MSXML2.XMLHttp"); }} varxmlhttp=XMLHttpFactory.createXMLHttp();
- 7. Singleton-EXPUserAgent = function UserAgent() { var u = navigator.userAgent, d = document; this.ie = typeofd.all != "undefined"; this.ns4 = typeofd.layers != "undefined";this.dom = typeofd.getElementById != "undefined";this.safari = /Safari/.test(u);this.moz = /Gecko/.test(u) && !this.safari;this.mie = this.ie && /Mac/.test(u); this.win9x = /Win9/.test(u) || /Windows 9/.test(u); this.o7 = /Opera 7/.test(u);this.supported = (typeofd.write != "undefined") && (this.ie || this.ns4 || this.dom);};
- 8. Singleton-EXPua = new function UserAgent() {var u = navigator.userAgent, d = document; this.ie = typeofd.all != "undefined"; this.ns4 = typeofd.layers != "undefined";this.dom = typeofd.getElementById != "undefined";this.safari = /Safari/.test(u);this.moz = /Gecko/.test(u) && !this.safari;this.mie = this.ie && /Mac/.test(u); this.win9x = /Win9/.test(u) || /Windows 9/.test(u); this.o7 = /Opera 7/.test(u);this.supported = (typeofd.write != "undefined") && (this.ie || this.ns4 || this.dom);};
- 10. Decorator-EXP// Create a Name Space myText = { }; myText.Decorators = { }; // Core base class myText.Core = function( myString ) {this.show = function( ) { return myString; }; } // First Decorator, to add quesCon mark to string myText.Decorators.addQuestionMark = function ( myString ) {this.show = function( ){ return myString.show( ) + '?'; }; } //Second Decorator, to make string Italics myText.Decorators.makeItalic = functioon( myString ) {this.show = function(){ return "<i>" + myString.show( ) + "</i>"; }; }
- 11. Decorator-EXP//Third Decorator, to make first character of sentence caps myText.Decorators.upperCaseFirstChar = function( myString ) {this.show = function( ){ varstr = myString.show( ); varucf = str.charAt(0).toUpperCase( );return ucf + str.substr( 1, str.length – 1 ); }; } // Set up the core String vartheString = new myText.Core( “this is a sample test string” ); // Decorate the string with Decorators theString = new myText.Decorator.upperCaseFirstChar( theString ); theString = new myText.Decorator.addQuestionMark( theString ); theString = new myText.Decorator.makeItalic( theString ); theString.show();
- 14. Bridge-EXPfunction getBeerById(id, callback) {// Make request for beer by ID, then return the beer data.asyncRequest('GET', 'beer.uri?id=' + id, function(resp) {// callback responsecallback(resp.responseText);});}addEvent(element, 'click', getBeerByIdBridge);function getBeerByIdBridge (e) {getBeerById(this.id, function(beer) {console.log('Requested Beer: '+beer);});}
- 18. Observer-EXP// The Observer Object – One who super sees all the print operations function printManager( ) { var queue = [ ]; // The attach method this.addJob = function(name, job) { queue.push( { ”name” : name, "job” : job } ); } // The detach method this.removeJob = function(job) { var _queue = [ ]; for(var i in queue) { if(queue[ i ].job == job) continue; else _queue.push( queue[ i ] ); } queue = _queue; } // The notify method this.doPrint = function( item ) { for ( var i in queue ) { queue[ i ].job.call( this, item );}} }
- 19. Observer-EXPvar p = new printManager(); // Publishers are in charge of "publishing” function printWithItalics( str ) { // The callback function – the print job alert( “<i>” + str + “</i>” ); } //Once subscribers are notified their callback functions are invokedp.addJob( "italics", printWithItalics); // Notify the observer about a state change p.doPrint("this is a test");
- 23. Strategy-EXPvar Button = function(submit_func, label) {this.label = label; return { on_submit : function(numbers) { return submit_func(numbers); } };};var numbers = [1,2,3,4,5,6,7,8,9];
- 24. Strategy-EXPvar sum = function(n) { var sum = 0; for ( var a in n ) { sum = sum + n[a]; } return sum;}; var a = new Button(sum, "Add numbers");var b = new Button(function(numbers) { return numbers.join(','); }, "test2");a.on_submit(numbers);b.on_submit(numbers);
- 26. Command-EXPvar Calculator={// additionadd: function(x,y) {return x+y;},// subtractionsubstract: function(x, y) {return x-y;},// multiplicationmultiply: function(x, y) {return x*y;},// divisiondivide: function(x, y) {return x/y;},};
- 27. Command-EXPCalculator.calc=function(command) {return Calculator[command.type](command.opl,command.op2);};Calculator.calc({type: "add",opl:1,op2:1});Calculator.calc({type: "Substract",opl:6,op2:2});Calculator.calc({type: "multiply",opl:5,op2:2));Calculator.calc({type: "divide",opl:8,op2:4));