Created
March 25, 2013 10:28
-
-
Save lynxerzhang/5236235 to your computer and use it in GitHub Desktop.
addWeak方法利用Dictionary可以针对键设置弱引用, 将值传入, 获取该值则是通过一个自定义键(比如任意字符串)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package | |
{ | |
import flash.utils.Dictionary; | |
/** | |
* this class inspiration from gskinner.com | |
* @see wwww.gskinner.com | |
*/ | |
public class WeakMap | |
{ | |
private var weakConfig:Dictionary; | |
public function WeakMap():void{ | |
weakConfig = new Dictionary(false); | |
} | |
/** | |
* key is just a marker, and value is weak value | |
* @param key | |
* @param value | |
* @see flash.utils.Dictionary | |
*/ | |
public function addWeak(key:*, value:*):void{ | |
if(!(key in weakConfig)){ | |
weakConfig[key] = new Weak(value); | |
} | |
} | |
/** | |
* remove specfied key-value pair | |
* @param key | |
*/ | |
public function removeWeak(key:*):void{ | |
if(key in weakConfig){ | |
weakConfig[key] = undefined; | |
delete weakConfig[key]; | |
} | |
} | |
/** | |
* record weakMap's key-value pair count | |
* @return | |
*/ | |
public function sumAvailable():int{ | |
var count:int = 0; | |
for(var item:* in weakConfig){ | |
if(weakConfig[item].contain()){ | |
count++; | |
} | |
} | |
return count; | |
} | |
/** | |
* iterate weakMap and delete the record value has been gc's key | |
*/ | |
public function refresh():void{ | |
for(var item:* in weakConfig){ | |
if(!(weakConfig[item].contain())){ | |
weakConfig[item] = undefined; | |
delete weakConfig[item]; | |
} | |
} | |
} | |
} | |
} | |
import flash.utils.Dictionary; | |
internal class Weak | |
{ | |
private var map:Dictionary = new Dictionary(true); | |
public function Weak(key:*):void{ | |
map[key] = true; | |
} | |
/** | |
* get the weak value | |
* @return | |
*/ | |
public function get():*{ | |
for(var item:* in map){ | |
return item; | |
} | |
return null; | |
} | |
/** | |
* check is whether contain | |
* @return | |
*/ | |
public function contain():Boolean{ | |
return get() != null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment