Flex 中函数队列的实现 很好用在TOP应用大赛中学得的FUNCTION QUEUE
在做TOP大赛的时候,我遇到过这样的问题。对于N个商品他们处理的方式不尽然相同(有M种处理方式)。
首先,我使用了很暴力的一个个函数写(switch语句),写完后发现代码太长太繁琐。当我要修改函数是,甚至发现找不到这个函数了。
于是我将这些函数写成了一个类,但是发现还是过长,最后想到了函数队列。
通过函数队列可以将,函数通过队列管理,也可以保持代码的高度重用性和简洁性。
1.设置 FunctionsArray 在Flex 中 Array实际带有queue的性质。
通过Array.push可以达到进队的效果。
2.设置orderArray 保存执行函数执行顺序。
如 : orderArray = [0,1,2];
意思就是执行的顺序为 functionsArray[0],functionsArray[1],functionsArray[2],
3.执行functionsArray。
当要改变执行顺序时,只需要改变orderArray的顺序。
当然通过调整functions数组也是可以达到目的的不过比较繁琐。
下面是自己写的Flex代码:
[php] view plaincopy
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
- creationComplete="init();" layout="absolute">
- <mx:Script>
- <!--[CDATA[
- import mx.collections.ArrayCollection;
- // function queue
- private var funcArr:Array = new Array();
- //标记操顺序的队列
- private var orderArr:Array = [0,1,2];
- //执行前的字符串数组
- private var previous:Array = new Array('Nokia N81','Nokia N82','Nokia N85');
- //执行后的字符串数组
- private var next:Array = new Array();
- private var arrc:ArrayCollection ;
- private function init():void
- {
- initFuncArray();
- //执行函数队列
- // swapFunction(0,2);
- var i:int ;
- for( i = 0 ; i < previous.length ; i++)
- {
- next.push( funcArr[ orderArr[i] ](previous[i]) );
- }
- list1.dataProvider = previous;
- list2.dataProvider = next;
- }
- private function initFuncArray():void
- {
- funcArr.push(aFunction);
- funcArr.push(bFunction);
- funcArr.push(cFunction);
- }
- private function aFunction(str:String):String
- {
- return str + " costs :" + "$100" + "(FunctionA)";
- }
- private function bFunction(str:String):String
- {
- return str + " costs :" + "$200" + "(FunctionB)";
- }
- private function cFunction(str:String):String
- {
- return str + " costs :" + "$300" + "(FunctionC)";
- }
- private function swapFunction(swapIndex:int , swaptoIndex:int):void
- {
- var temp:Function = new Function();
- temp = funcArr[swaptoIndex];
- funcArr[swaptoIndex] = funcArr[swapIndex] ;
- funcArr[swapIndex] = temp;
- }
- private function setArray(arr:Array):void
- {
- }
- ]]-->
- </mx:Script>
- <mx:List x="152" y="31" width="73" id="list1" height="140"></mx:List>
- <mx:Label x="242" y="68" text="函数执行后→" width="92" fontSize="12"/>
- <mx:List x="325" y="31" height="140" width="223" id="list2"></mx:List>
- </mx:Application>