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

    1.继承AsEventDispatcher类可以发送事件,添加事件侦听

    package
    {
    	import flash.events.Event;
    	import flash.utils.Dictionary;
    
    	public class AsEventDispatcher
    	{
    		//[事件类型]=事件处理函数
    		private var receive:Dictionary = new Dictionary();
    		
    		public function AsEventDispatcher()
    		{
    		}
    		//添加接收者
    		public function addEventListener(type:String, listener:Function):void
    		{
    			receive[type] = listener;
    		}
    		//清除接收者
    		public function removeEventListener(type:String, listener:Function):void
    		{
    			trace("removeEventListener");
    			for(var _type:String in receive)
    			{
    				if(_type == type &&receive[_type] == listener)
    				{
    					delete receive[_type];
    				}
    			}
    		}
    		//发送事件
    		public function dispatchEvent(evt:AsEvent):void
    		{
    			for(var _type:String in receive)
    			{
    				if(_type == evt.type)
    				{
    					receive[evt.type](evt);
    				}
    			}
    		}
    	}
    }
    

    2. 通过dispatchEvent发出的事件都要是AsEvent,或者AsEvent的子类

    package
    {
    	public class AsEvent
    	{
    		private var _type:String;
    		public function AsEvent(_typeStr:String)
    		{
    			_type = _typeStr;
    		}
    		public function get type():String
    		{
    			return _type;
    		}
    	}
    }
    

    3.运行

    package
    {
    	public class cs extends AsEventDispatcher
    	{
    		public function cs()
    		{
    			this.addEventListener("Event", onEvent);
    			//this.removeEventListener("Event", onEvent);
    			this.dispatchEvent(new AsEvent("Event"));
    		}
    		private function onEvent(evt:AsEvent):void
    		{
    			trace("..."); //输出...
    		}
    	}
    }
    
  • 相关阅读:
    服务管理命令
    软件管理
    Qt软件打包与发布(windeployqt工具)
    03
    第一章 BP神经网络
    代理模式 与 Spring AOP
    java 回调机制
    HashTable 实现
    实现Singleton模式
    BST 汇总
  • 原文地址:https://www.cnblogs.com/mzbdadou/p/2111914.html
Copyright © 2011-2022 走看看