간만에 블로그 글쓰기- ㅋ (연휴가 좋긴 좋아- ㅋ)
이건 며칠전에 질문 받았던 내용인데
puremvc 프레임웍을 쓰는 중에 Proxy 클래스를 상속받은 클래스에서 dispatchEvent 메소드를 사용하고 싶다는 내용이었다.
이미 상속된 클래스가 아니었다면 EventDispatcher 를 상속하는 것이 가장 간단하고 효율적이었겠지만
또 EventDispatcher 클래스에서 상속되어진 DisplayObject 클래스의 상속에 경우에는 당연히 dispatchEvent메소드를 호출하면 되는 간단한 이야기 겠지만
어쨌든 Proxy 클래스에서 상속되어진 클래스에서 dispatchEvent 메소드를 사용하고 싶다는 것이었다.
sendNotification 메소드를 호출 하시면 되지 않을까요? 했지만 뭔가 필히 dispatchEvent 메소드가 필요하셨던것 같다. (왜 인지는 사실 이해 못했다.;;)
어쨌든 요점은 단일상속만을 지원하는 액션스크립트에서 EventDispatcher 를 상속할 수 없는 상황, 그리고 EventDispatcher 의 기능을 구현해야 하는 상황을 질문 하신 것으로 이해했다.
그래서 일단은 샘플코딩-
EventDispatchableProxy.as
package com.shallaazm.as3.example.model
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import org.puremvc.as3.patterns.proxy.Proxy;
/**
* EventDispatchableProxy.
* @author <a target="_self">shallaa@shallaazm.com</a>
*/
public class EventDispatchableProxy extends Proxy implements IEventDispatcher
{
public static const NAME:String = "eventDispatchableProxy";
public static const SOME_EVENT:String = "someEvent";
private var _eventDispatcher:EventDispatcher;
public function EventDispatchableProxy()
{
super(NAME);
_eventDispatcher = new EventDispatcher();
}
override public function onRegister():void {
// EventDispatcher를 상속한것과 같이 그대로 사용하시면 됩니다.
// 물론 실제적인 일은 _eventDispatcher 요놈이 해줄거구요-.
dispatchEvent(new Event(SOME_EVENT));
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {
_eventDispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
public function dispatchEvent(event:Event):Boolean {
return _eventDispatcher.dispatchEvent(event);
}
public function hasEventListener(type:String):Boolean {
return _eventDispatcher.hasEventListener(type);
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void {
_eventDispatcher.removeEventListener(type, listener, useCapture);
}
public function willTrigger(type:String):Boolean {
return _eventDispatcher.willTrigger(type);
}
}
}
이걸 데코레이터 패턴 이라고 부르던가- 일단 정확하지 않은 것이니 패스- ㅋ
사실 대부분은 몸으로 뛰면서 먼저 익인거라 명칭은 좀 약하다. ㅋ 대략 합성이라는 정도에서 이해하고 쭉 읽어보시면 알듯.
IEventDispatcher 인터페이스를 구현했고 인터페이스 메소드의 실제적인 처리는 _eventDispatcher 인스턴스가 하고 있다.
별로 대단한 팁은 아니지만 이 정도로 EventDispatchableProxy 클래스는 충분히 EventDispathcer 의 역활을 수행할 수 있다.
응용하기에 따라 정적인 클래스에서도 EventDispatcher 의 기능을 사용할 수 있다.
