安卓中有一个重要的控件ListView,安卓通过让用户实现BaseAdapter类来连接ListView和数据列表,将数据绑定显示在ListView中。适配器模式连接两个不兼容的接口,使两个不能一起工作的两个接口实现一起工作的功能。
例子通过模仿Android的ListView实现过程来验证适配器模式,类图结构如下:
实现代码:
var Adapter = Class.extend({ listview:null, dataChanged:function(){ if (this.listview != null) { listview.draw(); } }, getView:function(position){ return ""; }, getCount:function(){ return 0; }, getObject:function(index){ return null; }});var ListView = Class.extend({ id:null, adapter:null, ctor:function(_id){ this.id = _id; }, setAdapter:function(_adapter){ this.adapter = _adapter; _adapter.listview = this; }, setOnItemClick:function(_callback){ this.callback = String(_callback).replace(/^function(\s|\n)+(.+)\((.|\n)+$/,'$2'); }, draw:function(){ var txt = ""; if(this.adapter != null){ for(var i = 0;i < this.adapter.getCount();i++){ txt += "" + this.adapter.getView(i) + ""; } } document.getElementById(this.id).innerHTML = txt; }});var MyAdapter = Adapter.extend({ bean:[], ctor:function(_data){ this.bean = _data }, getCount:function(){ return this.bean.length; }, getView:function(position){ var data = this.bean[position]; var tmpl = "姓名${name}${sex}${age}${address}"; while(tmpl.indexOf("${") > 0){ var start = tmpl.indexOf("${"); var end = tmpl.indexOf("}"); var key = tmpl.substring(start,end+1); tmpl = tmpl.replace(key,data[key.replace("${","").replace("}","")]); } return tmpl; }, getObject:function(position){ return bean[position]; }});
运行的效果图:
适配器模式的优点主要是将两个没有关联的类连接在一起,提高了复用,正如上面的例子ListView作为列表可以用在任何场合,数据类也可以在任何场合下继续使用,适配器将两者连接成整体工作达到效果。
适配器过多会造成系统的混乱,不易于程序的可读性。