使用Singleton来实现Flash和Flex的通信。
Singleton是比较简单的一种设计模式。在MVC模式中,Model一般就是一个Singleton。
Flash IDE开发的应用与Flex交互是比较困难的,利用Singleton可以很容易的实现通信。
先写一个继承自EventDispatcher的Singleton:
Package {
import flash.events.EventDispatcher;
public class SingletonEventDispatcher extends EventDispatcher{
protected static var instance:SingletonEventDispatcher;
public function SingletonEventDispatcher(){
if(instance!=null)
throw new Error("SingletonEventDispatcher is a singlton.");
}
public static function getInstance():SingletonEventDispatcher{
if(instance==null)
instance=new SingletonEventDispatcher();
return instance;
}
}
}
Singleton的原则就是只有一个实例在被使用,这些实例被聚集或者组合在其它的类中,那些类共享这个实例。
在Flash中使用这个Singleton发送消息:
var dispatcher:SingletonEventDispatcher=SingletonEventDispatcher.getInstance();
dispatcher.dispatchEvent(new Event("flashSay"));
在Flex中监听这个事件:
var dispatcher:SingletonEventDispatcher=SingletonEventDispatcher.getInstance();
dispatcher.addEventListener("flashSay",callback);
如果只是修改Flex用到的SingletonEventDispatcher,给该类添加属性或者方法。而Flash用到的SingletonEventDispatcher不做任何变化,程序依然可以完好的运行。但是前提是没有使用新添加的属性和方法。因为后来加载进来的类会覆盖前者。