zoukankan      html  css  js  c++  java
  • 3)Javascript设计模式:Observer模式

    Observer模式

    var Observer = (function() {
    
    	var instance = null;
    
    	function Observe() {
    		this.events = {}
    	}
    
    	Observe.prototype.subscribe = function(eventName, callback) {
    		var actions = this.events[eventName];
    		if( !actions) {
    			actions = this.events[eventName] = [];
    		}
    		actions.push(callback);
    
    	};
    
    	Observe.prototype.publish = function(eventName) {
    		var args = Array.prototype.slice.call(arguments).slice(1);
    		var actions = this.events[eventName];
    		if(actions) {
    			for(var cb in actions) {
    				actions[cb].apply(null, args)
    			}
    		}
    		else {
    			console.log(eventName || '' + ' is not registered');
    		}
    	};
    
    	function returnFunction() {
    		if(!instance) {
    			instance = new Observe();
    		}
    		return instance;
    	}
    
    	returnFunction.toString = function() {
    		console.log('Use Observer() to get instance');
    	};
    
    	return returnFunction;
    
    })();
    
    
  • 相关阅读:
    Scanner类
    BufferedReader类
    打印类
    管道流
    内存操作流
    转换流——OutputStreamWriter类与InputStreamReader类
    Java字节流与字符流基本操作
    RandomAccessFile类
    File类
    Timer类和TimerTask类
  • 原文地址:https://www.cnblogs.com/human/p/5078559.html
Copyright © 2011-2022 走看看