javascript设计模式

来源:互联网 发布:linux 开启端口监听 编辑:程序博客网 时间:2024/05/16 11:58
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>设计模式</title></head><body><script>    /*    * 1、单件模式(单例模式)    * */   //只创建一个实例   var Singleton = (function(){       var instantiated;       function init(){           return {               publicMethod: function(){                   console.log("hello world");               },               publicProperty: 'test'           }       }       return {           getInstance: function(){               if(!instantiated){                   instantiated = init();               }               return instantiated;           }       }   })();   Singleton.getInstance().publicMethod();      //单例的应用场景   var SingletonTester = (function(){function Singleton(args){var args = args||{};this.name = 'SingletonTester';this.pointX = args.pointX||6;this.pointY = args.pointY||10;}var instance;var _static = {name: 'SingletonTester',getInstance: function(args){if(instance === undefined){instance = new Singleton(args);}return instance;}};return _static;   })();   var obj = SingletonTester.getInstance({pointX: 5});   console.log(obj);   var obj2 = SingletonTester.getInstance({pointX: 6});   console.log(obj2);   console.log(obj === obj2);   /*2、工厂模式在该模式下,代码将会根据具体的输入或其他既定规则,自行决定创建哪种类型的对象。   */var myApp = {};myApp.dom = {};myApp.dom.Text = function(){this.insert = function(where){var txt = document.createTextNode(this.url);where.appendChild(txt);}};myApp.dom.Link = function(){this.insert = function(where){var link = document.createElement('a');link.href = this.url;link.appendChild(document.createTextNode(this.url));where.appendChild(link);}};myApp.dom.Image = function(){this.insert = function(where){var im = document.createElement('img');im.src = this.url;where.appendChild(im);}};myApp.dom.factory = function(type){return new myApp.dom[type];}var o = myApp.dom.factory("Link");o.url = "http://www.baidu.com";o.insert(document.body);/*--------以上两个模式是与创建对象有关的模式----------*//*3、装饰器模式   扩展对象的功能   通过重载方法的形式添加新功能,该模式可以在被装饰者前面或者后面加上自己的行为以达到特定的目的。*/var tree = {};tree.decorate = function(){alert('make sure the tree won\'t fall.');}tree.getDecorator = function(deco){tree[deco].prototype = this;return new tree[deco];}tree.RedBalls = function(){this.decorate = function(){this.RedBalls.prototype.decorate();alert('Put on some red balls');}}tree.BlueBalls = function(){this.decorate = function(){this.BlueBalls.prototype.decorate();alert('Add blue balls');}}tree.Angel = function(){this.decorate = function(){this.Angel.prototype.decorate();alert('An angel on the top');}}tree = tree.getDecorator('BlueBalls');tree = tree.getDecorator('Angel');tree = tree.getDecorator('RedBalls');tree.decorate();console.log(1e309);//装饰者模式2function Macbook() {this.cost = function() {return 1000;}}function Memory(macbook) {this.cost = function() {return macbook.cost() + 75;}}function BlurayDrive(macbook) {this.cost = function () {return macbook.cost() + 300;}}function Insurance(macbook) {this.cost = function() {return macbook.cost() + 250;}}var myMacbook = new Insurance(new BlurayDrive(new Memory(new Macbook())));console.log(myMacbook.cost());/*4、观察者模式观察者模式(有时也称为订阅者/发行商模式)是一种行为型模式,主要用于处理不同对象之间的交互通信问题。观察者模式中通常会包含两类对象:   ①、一个或多个发行商对象:当有重要的事情发生时,会通知订阅者。   ②、一个或多个订阅者对象:它们追随一个或多个发行商,监听它们的通知,并作出相应的反应。*//*观察者对象中应该有如下属性和方法:4.1、由回调函数构成的订阅者数组。4.2、用于添加和删除订阅者的addSubscriber()和removeSubscriber()方法。4.3、publish()方法,授受并传递数据给订阅者。4.4、make()方法,将任意对象转变为一个发行商并为其添加上述方法。*///观察者对象的实现var observer = {//添加订阅者addSubscriber: function(callback) {this.subscribers[this.subscribers.length] = callback;},//删除订阅者removeSubscriber: function(callback) {for (var i = 0; i < this.subscribers.length; i++){if(this.subscribers[i] === callback){delete(this.subscribers[i]);}}},//publish: function(what){for(var i = 0; i < this.subscribers.length; i++) {if(typeof this.subscribers[i] === 'function'){this.subscribers[i](what);}}},//将任意对象转变为发行商make: function(o) {for(var i in this){o[i] = this[i];o.subscribers = [];}}};//每当新博客准备好时,就会调用publish()方法var blogger = {writeBlogPost: function(){var content = 'Today is' + new Date();this.publish(content);}};//每当新一期的报刊出来时,就会调用publish()方法。var la_times = {newIssue: function() {var paper = 'Martians have landed on Earth';this.publish(paper);}};observer.make(blogger);observer.make(la_times);//准备两个简单对象var jack = {read: function(what){console.log('I just read that ' + what);}};var jill = {gossip: function(what) {console.log('you didn\'t hear it from me, but ' + what);}};        //开始订阅blogger.addSubscriber(jack.read);blogger.addSubscriber(jill.gossip);la_times.addSubscriber(jack.read);        //写博客后推送,订阅者都会接收到消息blogger.writeBlogPost();        //取消其中的一个订阅者blogger.removeSubscriber(jack.read);la_times.newIssue();        //再写博客推送,取消订阅的人接收不到消息了blogger.writeBlogPost();</script></body></html>

0 0
原创粉丝点击