加载中...

适配器模式


适配器模式

适配器模式 将一个对象或者类的接口翻译成某个指定的系统可以使用的另外一个接口。

适配器基本上允许本来由于接口不兼容而不能一起正常工作的对象或者类能够在一起工作.适配器将对它接口的调用翻译成对原始接口的调用,而实现这样功能的代码通常是最简的。

我们可能已经用过的一个适配器的例子就是jQuery的jQuery.fn.css()方法,这个方法帮助规范了不同浏览器之间样式的应用方式,使我们使用简单的语法,这些语法被适配成为浏览器背后真正支持的语法:

  1. // Cross browser opacity:
  2. // opacity: 0.9; Chrome 4+, FF2+, Saf3.1+, Opera 9+, IE9, iOS 3.2+, Android 2.1+
  3. // filter: alpha(opacity=90); IE6-IE8
  4. // Setting opacity
  5. $( ".container" ).css( { opacity: .5 } );
  6. // Getting opacity
  7. var currentOpacity = $( ".container" ).css('opacity');

将上面的代码变得可行的相应的jQuery核心css钩子在下面:

  1. get: function( elem, computed ) {
  2. // IE uses filters for opacity
  3. return ropacity.test( (
  4. computed && elem.currentStyle ?
  5. elem.currentStyle.filter : elem.style.filter) || "" ) ?
  6. ( parseFloat( RegExp.$1 ) / 100 ) + "" :
  7. computed ? "1" : "";
  8. },
  9. set: function( elem, value ) {
  10. var style = elem.style,
  11. currentStyle = elem.currentStyle,
  12. opacity = jQuery.isNumeric( value ) ?
  13. "alpha(opacity=" + value * 100 + ")" : "",
  14. filter = currentStyle && currentStyle.filter || style.filter || "";
  15. // IE has trouble with opacity if it does not have layout
  16. // Force it by setting the zoom level
  17. style.zoom = 1;
  18. // if setting opacity to 1, and no other filters
  19. //exist - attempt to remove filter attribute #6652
  20. if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
  21. // Setting style.filter to null, "" & " " still leave
  22. // "filter:" in the cssText if "filter:" is present at all,
  23. // clearType is disabled, we want to avoid this style.removeAttribute
  24. // is IE Only, but so apparently is this code path...
  25. style.removeAttribute( "filter" );
  26. // if there there is no filter style applied in a css rule, we are done
  27. if ( currentStyle && !currentStyle.filter ) {
  28. return;
  29. }
  30. }
  31. // otherwise, set new filter values
  32. style.filter = ralpha.test( filter ) ?
  33. filter.replace( ralpha, opacity ) :
  34. filter + " " + opacity;
  35. }
  36. };

还没有评论.