zoukankan      html  css  js  c++  java
  • js之观察者模式

    1.观察者模式:在对象之间定义一对多的依赖,这样一来,当一个对象改变状态,依赖它的对象都会收到通知,并自动更新。

    2.OO原则:为交互对象之间的松耦合设计而努力。

      松耦合的设计之所以能让我们建立有弹性的OO系统,能够应对变化,是因为对象之间的互相依赖降到了最低。观察者模式提供了一种对象设计,让主题和观察者之间松耦合。当两个对象之间松耦合,它们依然可以交互,但是不太清楚彼此的细节。

    3.文件结构

    4.index.html文件下面

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8" />
    		<title></title>
    	</head>
    	<body>
    		
    	</body>
    	<script type="text/javascript" src="js/require.js" data-main = "js/index"></script>
    </html>
    

     5.index.js文件

    require([
    	"./coms1",
    	"./coms2",
    	"./engine"
    ],function(coms1,coms2,engine){
    	
    	
    	engine.register(coms1);
    	engine.register(coms2);
    	
    	coms1.createNew(engine);
    	coms2.createNew(engine);
    	
    });
    

    6.engine.js

    define([],function(){
    	
    	var comList = [];
    	
    	return {
    		register:function(com){
    			comList.push(com);
    		},
    		upData:function(Msg){
    			this.send(Msg);
    		},
    		send:function(Msg){
    			for(var i = 0; i < comList.length; i++){
    				comList[i].watch(Msg);
    			}
    		}
    	}
    });
    

    7. coms1.js

    define([],function(){
    	
    	
    	return {
    		createNew:function(engine){
    			engine.upData("coms1");
    		},
    		watch:function(Msg){
    			console.log(Msg);	
    		}
    	}
    });
    

    8.coms2.js

    define([],function(){
    		
    	return {
    		createNew:function(engine){
    			engine.upData("coms2");
    		},
    		watch:function(Msg){
    			console.log(Msg);
    		}
    	}
    });
    

    9.运行index.html,控制太输出

      

      

    10.总结:观察者模式,降低组件之间的耦合,又可以让组件之间进行通信,每个组件,必须注册到引擎当中,才能参与通信,引擎会收到所有注册的组件的消息,再转发给所有的组件,达到组件之间通信的效果

     

  • 相关阅读:
    Hive初识(一)
    图解HTTP总结(8)——确认访问用户身份的认证
    Android 7.0 照相 FileUriExposedException
    activity跳转的一些坑
    gopath配置
    android项目中记录
    一些趣味性总结(JAVA)
    http的response遇到illegalstateexception解决办法
    django demo
    Error:Execution failed for task ':app:transformClassesWithDexForDebug'解决方法
  • 原文地址:https://www.cnblogs.com/muamaker/p/6472408.html
Copyright © 2011-2022 走看看