Tuesday 24 May 2011

Observer Design Pattern in Flex


 how Observer Pattern works:
First of all you must create an Interface (IObserver) that has an update method that will be called from Observer manager when a notification will be called:
public interface IObserver {
    function update(_notification:String):void;
}
Then you must have an Observer Manager that manage all objects that implements IObserver interface.
This manager will have 3 public methods: subscribe, unsubscribe and notify.
You call subscribe when you want to add an object that is update from Observer; unsubscribe when you remove an object from a displaylist or if you don’t need to update anymore  and notify when you want to notify something to all subscribed objects:
public class ObserverManager {
private static var instance : ObserverManager;
private var observerData : Array;
public function ObserverManager():void{
observerData = new Array();
}
public static function getInstance() : ObserverManager{
if(instance == null)
instance = new ObserverManager();
return instance;
}
public function subscribe(observer:IObserver):void{
observerData.push(observer);
}
public function unsubscribe(observer : IObserver) : void {
var totObs:int = observerData.length;
for(var i:int = 0; i < totObs; i++){
if(observer === observerData[i]){
observerData.splice(i, 1);
break;
}
}
}
              
       public function notify(_notification:String):void{
var totObs:int = observerData.length;
for(var i:int = 0; i < totObs; i++){
observerData[i].update(_notification);
}
}
}
Ok now you are ready to work with observer, so we create an object that implements IObserver and another one that add on displaylist all IObserver objects and notify to all some notifications:
custom button that implements IObserver interface:
public class ObserverButton extends Button implements IObserver

{

 public static const HIDE_BUTTON:String = "hideBtnEvt";

 public static const SHOW_BUTTON:String = "showBtnEvt";

  

 public function ObserverButton()

 {

  super();   

 }

  

 public function update(_notification:String):void

 { 

  switch(_notification){   

   case HIDE_BUTTON:

    this.alpha = .2;

    break;

    

   case SHOW_BUTTON:

    this.alpha = 1;

    break;

  }   

 }

}

subscribe some custom buttons to observer manager:   

protected var observer:ObserverManager;

protected function init():void{    

 observer = ObserverManager.getInstance();

 for(var i:int = 0; i < 100; i++){   

  var btn:ObserverButton = new ObserverButton();

  btn.label = i.toString()

  addElement(btn);




  if((i & 1) == 0)

   observer.subscribe(btn);

     

  btn.x = Math.random() * 800;

  btn.y = Math.random() * 500 + 70;

     

Run Example  

No comments:

Post a Comment