zoukankan      html  css  js  c++  java
  • flex框架pureMVC的使用:第一步

     

    学习标记:转自:http://ioryioryzhan.iteye.com/blog/212110

    做flex做久做大了,使用一个框架便是自然而然的事情。这样程序才会更健壮,更易于扩展,更易于维护。pureMVC足够简单,核心也只有十来个类,是一个轻量级的Flex框架,只一天的时间,就可以学通,没有理由不用它的。

     

        麻雀虽小,五脏俱全,pureMVC,直译过来就是“纯MVC”,是一个MVC框架。官方的中文文档有44页,放在附件中,可以下载了看。推荐一个入门的文章给大家。(http://riachina.com/showtopic-11011.html ),里面有足够全面的介绍。这里我想利用一个更加简单的图片展示的例子来展示pureMVC的使用细节。先看效果:

     

     

     

     

      介绍一下这个应用。程序一开始便请求展示的图片信息(包括图片的链接以及名称),得到信息后便可以通过两个按钮进行逐张的浏览。这个例子太简单了,以致根本没有必要去用pureMVC,这里我只是想借用它来介绍pureMVC如何使用的。

     

        如果将上面的例子假设为做菜,哈哈,就会更有意思了。两个 Button ,一个 Image 与 Label 便是锅碗瓢盆,而图片的信息便是原料,而怎么样来炒,便要看菜谱了。pureMVC 的设计者估计也是做菜的高手。这些对他们来说就是 Model (原料), View (锅碗瓢盆), Controller (菜谱),三个都是单例模式。同时他们还设计出一个厨师,叫 Facade ,由它来调度上面三个,也是单例的。

     

        一切从 Facade 开始,它实列化 Model , View , Controller 。MVC 也找了一些帮手, Model 找到的是 Proxy 们,代理?好像翻译得不对。不管,以后的数据就靠它了。View 找的是 Mediator,它们负责UI,Controller 找的是 Command,不过 Command 性格比较怪,做完一次任务就不干了,也就是短生命同期的。每次用它 pureMVC 都会重新创建。所以只能用它来做业务逻辑,而不要将长期的数据放在里面。

     

        pureMVC 消息采用的观察者模式,每次做完一件事情,就可以向外发出一个 Notification  (不是 Flex 里的 Event 哟),就像向外宣布“事情做完了”,具体谁关心就管不着了。这里 Proxy 有点特别,它们只会向外发出 Notification ,但从不接收,只关心自己的数据模型。这很有意义,想想人家叫 “纯MVC” 嘛。

     

        好了,开始做这个例子。刚开始学东西的时候总会发现,文档都看懂了,东西好像都会了。真要用它做东西,却不知道怎么下手。所以还要再好好分析下程序,看看怎么样下手。

     

       首先界面上就四个控件,两个Button ,一个 Image 和 一个Label ,从功能上可以分为两类,两个 Button 是用来作控制的, Image 与 Label 用来显示图片及图片名称。和 UI 对应的是 Mediator ,所以要定义两个 Mediator 类。如果程序变大了,也可以这样来划分,千万不要为每个按钮作一个 Mediator ,也不要整个 Application 才一个 Mediator,最好按功能来划分。

     

       然后再来看 Model ,本例中的数据只有一项,便是要显示的图片资料。所以只要求定义一个 Proxy 用来数据交互就够了。flex 得到数据的方式有许多种,如HttpService ,RemoteObject ,XMLSocket等,但不管什么,总之都是从其他地方得到有用的信息,然后将它变成自己自己的程序能够理解的形式。当然解析数据,大多是业务逻辑( Controller )的工作了。

     

       再看Controller这边,Controller 涉及到业务 ,本例中业务有程序启动(StartUp),还有个就是得到图片信息。还有吗,好像没有了。两个Command就可以应付了。

     

        好了,可以动手编码了。

     

    定义两个Mediator (ImageMediator 与 ControlBtnsMediator,继承Mediator类,实现IMediator接口),

    两个Command ( StartUpCommand 与 GetUrlListCommand,继承SimpleCommand类,实现ICommand) 

    以及一个Proxy (ImageUrlListProxy ,继承Proxy,实现IProxy接口)

    一个图片信息类(ImageUrlVO),用来存放单张图片信息。

    一个Facade (MyAppFacade 继承Facade,实现IFacade接口)

     

    程序的包结构:

    同时思考需要的 Notification ,它是将整个框架联系起来的关键。

    1.程序开始便要启动 StrartUpCommand,所以StrartUpCommand 要关注 "app_startup"

    2.StrartUpCommand主要完成Proxy与Mediator的注册,完成后便可以启动GetUrlListCommand,所以GetUrlListCommand应关注"app_startup_over"

    3.GetUrlListCommand 通过 ImageUrlListProxy去获取图片信息,前面提到 ImageUrlListProxy是不能接收Notification,所以GetUrlListCommand要直接调用ImageUrlListProxy的public成员函数loadUrlList()去获取图片信息

    4.ImageUrlListProxy 得到图片链接以后,便可以对外宣布“图片信息已经得到了”,即对外Send一个"url_load_complete"的Notification,关注这一Notification的自然是ImageMediator,它直接将图片信息保存起来,并显示第一张图片内容

    5.ControlBtnsMediator不需要关注任何Notification,不过点击两个按钮时会向外Send Notification ("next_image" 与 "prev_image"),,通知显示下一张或上一张图片。关注这两个Notification的自然是ImageMediator了。

     

    好了,流程都介绍完了,来看代码。

     

    先定义类 ImageUrlVO 的代码如下:

     1 package MyApp.Model.VO  
     2 {  
     3     public class ImageUrlVO  
     4     {  
     5         public var url:String;    //图片链接  
     6         public var name:String;  //图片名称  
     7         public function ImageUrlVO(url:String,name:String){  
     8             this.url = url;  
     9             this.name = name;  
    10         }  
    11     }  
    12 }  

     

        接下来从程序的执行步骤依次看各个类的代码。

     

        主界面 HelloPureMVC.mxml:

     1 <?xml version="1.0" encoding="utf-8"?>  
     2 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"  
     3   width="200" height="200" creationComplete="initApp()">   
     4   <mx:Script>  
     5     <![CDATA[ 
     6         import MyApp.MyAppFacade; 
     7         public function initApp():void{ 
     8             var facade:MyAppFacade = MyAppFacade.getInstance(); 
     9             facade.startup( this ); 
    10         } 
    11     ]]>  
    12   </mx:Script>  
    13  <mx:Canvas id="mainContainer" width="100%" height="100%">  
    14   <mx:Label id="nameLabel" x="87.5" y="0"/>  
    15   <mx:Image id="image" x="30" y="20" width="140" height="140"/>  
    16   <mx:Button x="10" y="168" label="上一张" id="btnPrev"/>  
    17   <mx:Button x="125" y="168" label="下一张" id="btnNext"/>  
    18    
    19  </mx:Canvas>  
    20 </mx:Application>  

      主界面现在只关注布局就够了。同时还要注意到里面的initApp()函数,它首先得到Facade实例,再调用其 startup() 函数启动整个PureMVC框架。

      跟进去再让看 MyAppFacade 的实现。

     

     1 package MyApp  
     2 {  
     3     import MyApp.Controller.GetUrlListCommand;  
     4     import MyApp.Controller.StartUpCommand;  
     5     import org.puremvc.as3.interfaces.IFacade;  
     6     import org.puremvc.as3.patterns.facade.Facade;  
     7   
     8     public class MyAppFacade extends Facade implements IFacade  
     9     {  
    10         public static const APP_STARTUP:String = "app_startup";  
    11         public static const APP_STARTUP_OVER:String = "app_startup_over";  
    12           
    13         public function MyAppFacade()  
    14         {  
    15             super();  
    16         }  
    17           
    18         public static function getInstance():MyAppFacade{  
    19             if(instance==null) instance = new MyAppFacade();  
    20             return instance as MyAppFacade;  
    21         }                                     
    22         override protected function initializeController():void{  
    23             super.initializeController();  
    24             //register some Commands  
    25             registerCommand(APP_STARTUP,StartUpCommand);  
    26             registerCommand(APP_STARTUP_OVER,GetUrlListCommand);  
    27         }  
    28         public function startup(app:Object):void{         
    29             sendNotification(APP_STARTUP,app);    
    30         }     
    31           
    32     }  
    33 }  

        可见Facade做的事情很简单, initializeController() 是用来初始化Controller的,这个函数是建立各个Notification与Command映射的地方,有了上面的流程分析,

    1 registerCommand(APP_STARTUP,StartUpCommand);  
    2 registerCommand(APP_STARTUP_OVER,GetUrlListCommand); 

    这两行这很容易了。startup()函数,终于轮到它了。它只做了一件事情,就是向外派发一个APP_STARTUP的Notification,关注它的是前面已经建立映射的StartUpCommand,pureMVC会实例化一个StartUpCommand的实例,并将app作为参数,调用其execute函数。

    tip:通常用一个字符串来标识一个Notification,不过建议用字符常量。减少犯错的可能。

     

     再来看StartUpCommand的代码:

     1 package MyApp.Controller  
     2 {  
     3     import MyApp.Model.ImageUrlListProxy;  
     4     import MyApp.MyAppFacade;  
     5     import MyApp.View.ControlBtnsMediator;  
     6     import MyApp.View.ImageMediator;  
     7     import org.puremvc.as3.interfaces.ICommand;  
     8     import org.puremvc.as3.interfaces.INotification;  
     9     import org.puremvc.as3.patterns.command.SimpleCommand;  
    10   
    11     public class StartUpCommand extends SimpleCommand implements ICommand  
    12     {  
    13         public function StartUpCommand()  
    14         {  
    15             super();  
    16         }         
    17         override public function execute(notification:INotification):void  
    18         {  
    19             var app:HelloPureMVC = notification.getBody() as HelloPureMVC;  
    20             //注册代理(proxy)  
    21             facade.registerProxy( new ImageUrlListProxy( ImageUrlListProxy.NAME ) );  
    22             //注册中介器  
    23             facade.registerMediator( new ImageMediator(   
    24                    ImageMediator.NAME,   
    25                    {  
    26                      image:app.image,  
    27                      nameLabel:app.nameLabel  
    28                    }  
    29             ) );  
    30               
    31             facade.registerMediator( new ControlBtnsMediator(  
    32                     ControlBtnsMediator.NAME ,  
    33                     {  
    34                         btnNext:app.btnNext,  
    35                         btnPrev:app.btnPrev  
    36                     }  
    37             ) );  
    38             //通知已经初始化完毕  
    39             sendNotification(MyAppFacade.APP_STARTUP_OVER,app);               
    40         }  
    41           
    42     }  
    43 }  

        只有一个execute()函数,它的任务便是注册前面提到的两个Mediator和一个Proxy,用到的是registerProxy()与registerMediator()两个函数,完成注册后便可以对外Send MyAppFacade.APP_STARTUP_OVER 了。关注这一Notificator的便是前面已经建立映射的 GetUrlListCommand 。同样一个 GetUrlListCommand 会被实例化,再调用其execute()函数。

     

    tip:Proxy类的构造函数需要一个proxyName:String作为其唯一标识,可以通过这一字符串得到该Proxy的引用,这里也建议使用字符常量

     

     1 package MyApp.Controller  
     2 {  
     3     import MyApp.Model.ImageUrlListProxy;  
     4     import org.puremvc.as3.interfaces.ICommand;  
     5     import org.puremvc.as3.interfaces.INotification;  
     6     import org.puremvc.as3.patterns.command.SimpleCommand;  
     7   
     8     public class GetUrlListCommand extends SimpleCommand implements ICommand  
     9     {  
    10         public function GetUrlListCommand()  
    11         {  
    12             super();  
    13         }  
    14           
    15         override public function execute(notification:INotification):void  
    16         {  
    17             //得到图片链接  
    18             (facade.retrieveProxy( ImageUrlListProxy.NAME ) as ImageUrlListProxy).loadUrlList();          
    19         }  
    20           
    21     }  
    22 } 

        好简单,呵呵,得到 ImageUrlListProxy 的实例,调用其loadUrlList()函数就可以了。前面提到Proxy不会去接收任何Notification,所以只能通过调用其成员函数的形式来使用它。

     看看ImageUrlListProxy的代码:

     

     1 package MyApp.Model
     2 {
     3     import MyApp.Model.VO.ImageUrlVO;
     4     import org.puremvc.as3.interfaces.IProxy;
     5     import org.puremvc.as3.patterns.proxy.Proxy;
     6 
     7     public class ImageUrlListProxy extends Proxy implements IProxy
     8     {
     9         public static const NAME:String = "ImageUrlListProxy";
    10         
    11         //定义一些Notification字符常量
    12         public static const URL_LOAD_COMPLETE:String = "url_load_complete";
    13         
    14         public function ImageUrlListProxy(proxyName:String=null, data:Object=null)
    15         {            
    16             super(proxyName,data);
    17         }        
    18         public function loadUrlList():void{            
    19             data = new Array();
    20             //push六张图片的Url
    21             data.push(new ImageUrlVO("http://www.mjbox.com/r/io/ioryioryzhan/pic1.jpg","卡莫"));
    22             data.push(new ImageUrlVO("http://www.mjbox.com/r/io/ioryioryzhan/pic2.jpg","李时珍"));
    23             data.push(new ImageUrlVO("http://www.mjbox.com/r/io/ioryioryzhan/pic3.jpg","姚明"));
    24             data.push(new ImageUrlVO("http://www.mjbox.com/r/io/ioryioryzhan/pic4.jpg","费得了"));
    25             data.push(new ImageUrlVO("http://www.mjbox.com/r/io/ioryioryzhan/pic5.jpg","伍兹"));
    26             data.push(new ImageUrlVO("http://www.mjbox.com/r/io/ioryioryzhan/pic6.jpg","不认得"));    
    27             //通知image Url已经全部得到了
    28             if(data==null)trace("data is null");
    29             sendNotification( URL_LOAD_COMPLETE    ,data );                    
    30         }            
    31     }
    32 }

      loadUrlList()函数去得到图片信息,由于没有后台,所以只能用这种直接写硬编码的方式了 ,会有很多方式得到数据,如前面提到的HttpService及RemoteObject等。同步的异步的都可以用。

     Proxy 有一个data成员,是个Object,用来盛放接收到的数据。得到数据后便可以Send一个Notification (URL_LOAD_COMPLETE)了。接下来看关注这个Notification的ImageMediator。

     

     1 package MyApp.View
     2 {
     3     import mx.controls.Alert;
     4     import mx.controls.Image;
     5     import mx.controls.Label;
     6     
     7     import MyApp.Model.ImageUrlListProxy;
     8     import MyApp.Model.VO.ImageUrlVO;
     9     import org.puremvc.as3.interfaces.IMediator;
    10     import org.puremvc.as3.interfaces.INotification;
    11     import org.puremvc.as3.patterns.mediator.Mediator;
    12 
    13     public class ImageMediator extends Mediator implements IMediator
    14     {
    15         public static const NAME:String = "ImageMediator";
    16         
    17         private var arrayOfImage:Array=null; 
    18         private var currentIndex:int=-1;
    19         
    20         public function ImageMediator(mediatorName:String=null, viewComponent:Object=null)
    21         {
    22             super(mediatorName, viewComponent);
    23         }
    24         
    25         
    26         override public function listNotificationInterests():Array{
    27             //列出感兴趣的Notification
    28             return [
    29               ImageUrlListProxy.URL_LOAD_COMPLETE,
    30               ControlBtnsMediator.NEXT_IMAGE,
    31               ControlBtnsMediator.PREV_IMAGE        
    32             ];
    33         }    
    34         
    35         override public function handleNotification(notification:INotification):void{            
    36             switch(notification.getName()){
    37                 case ImageUrlListProxy.URL_LOAD_COMPLETE:        
    38                     arrayOfImage = notification.getBody() as Array;   
    39                     if(arrayOfImage){
    40                         trace(arrayOfImage.length);
    41                         trace((viewComponent.nameLabel as Label).text);
    42                         (viewComponent.nameLabel as Label).text = (arrayOfImage[0] as ImageUrlVO).name;
    43                         (viewComponent.image as Image).source = (arrayOfImage[0] as ImageUrlVO).url;
    44                         currentIndex = 0;
    45                     }else{
    46                         Alert.show("没有得到图片链接","错误");
    47                     }
    48                     
    49                 break;    
    50                 case ControlBtnsMediator.NEXT_IMAGE:
    51                     if(currentIndex==-1)break;
    52                     if(currentIndex >= arrayOfImage.length-1 ){Alert.show("已经是最后一张图片了","错误");}
    53                     else{
    54                         trace((viewComponent.nameLabel as Label));
    55                         (viewComponent.nameLabel as Label).text = (arrayOfImage[currentIndex+1] as ImageUrlVO).name;
    56                         (viewComponent.image as Image).source = (arrayOfImage[currentIndex+1] as ImageUrlVO).url;
    57                         ++currentIndex;
    58                     }                    
    59                 break;
    60                 case ControlBtnsMediator.PREV_IMAGE:
    61                 if(currentIndex==-1)break;
    62                 if(currentIndex ==0 ){Alert.show("目前是第一张图片","错误");}
    63                     else{
    64                         (viewComponent.nameLabel as Label).text = (arrayOfImage[currentIndex+-1] as ImageUrlVO).name;
    65                         (viewComponent.image as Image).source = (arrayOfImage[currentIndex-1] as ImageUrlVO).url;
    66                         --currentIndex;
    67                     }
    68                 break;            
    69                 default:break;
    70             }            
    71         }                    
    72     }
    73 }

      ImageMediator除了关注ImageUrlListProxy.URL_LOAD_COMPLETE外,还要关注ControlBtnsMediator.NEXT_IMAGE以及ControlBtnsMediator.PREV_IMAGE,即为示下一张或上一张图片。

     

      具体怎么将Mediator与其关注的Notification关联起来呢,listNotificationInterests(),就是它了。它要求返回一个字符数组,在注册这个Mediator时,该函数就会被调用,之后,当一个Notification被发送时,如果该Notification的字符串存在于这个字符数组时,这个Mediator就能接收到。

     

     处理Notification是在handleNotification()函数内进行的,通过switch/case的方式,对不同的Notification进行不同的处理。会MFC的筒子们一定会觉得好熟悉啊,在 MFC 里,窗口函数也是这样来处理消息的。

     

     具体代码就不分析了,很简单的。

     

     最后就只有ControlBtnsMediator了。

     

     1 package MyApp.View
     2 {
     3     import flash.events.MouseEvent;
     4     
     5     import mx.controls.Button;
     6     
     7     import org.puremvc.as3.interfaces.IMediator;
     8     import org.puremvc.as3.patterns.mediator.Mediator;
     9 
    10     public class ControlBtnsMediator extends Mediator implements IMediator
    11     {
    12         public static const NAME:String = "ControlBtnsMediator";
    13         
    14         public static const NEXT_IMAGE:String = "next_image";
    15         public static const PREV_IMAGE:String = "prev_image";
    16         
    17         public function ControlBtnsMediator(mediatorName:String=null, viewComponent:Object=null)
    18         {
    19             super(mediatorName, viewComponent);
    20             (viewComponent.btnPrev as Button).addEventListener(MouseEvent.CLICK,onClickPrev);
    21             (viewComponent.btnNext as Button).addEventListener(MouseEvent.CLICK,onClickNext);
    22         }        
    23         private function onClickPrev(e:MouseEvent):void{
    24             sendNotification(PREV_IMAGE);
    25         }
    26         private function onClickNext(e:MouseEvent):void{
    27             sendNotification(NEXT_IMAGE);
    28         }
    29 
    30     }
    31 }

      注册监听,响应时发送相应的Notification。

      好了,都介绍完了,点击运行吧。

     

     

    同时这张图也可以用于理解mvc框架流程

     

     

     

     

    在这图书馆两分钟断一下的无线网中,我哭着整理完了这篇文章,真给这破网跪了,但还是很安慰,我整理好了,当初学这个的时候因为不懂puremvc这个框架,后面是这篇文章了我启发,希望有需要的朋友可以看看。一起进步。2013/12/11 郑年锦图书馆

  • 相关阅读:
    位图
    3. 资源管理(条款:13-17)
    70. Implement strStr() 与 KMP算法
    69. Letter Combinations of a Phone Number
    68. Longest Common Prefix
    67. Container With Most Water
    66. Regular Expression Matching
    65. Reverse Integer && Palindrome Number
    波浪理论
    MACD理解
  • 原文地址:https://www.cnblogs.com/ning1121/p/3470107.html
Copyright © 2011-2022 走看看