鍍金池/ 教程/ HTML/ 適配器模式
中介者模式
MVVM
亨元模式
設計模式分類概覽表
ES Harmony
組合模式
CommonJS
jQuery 插件的設計模式
外觀模式
觀察者模式
建造者模式
構(gòu)造器模式
外觀模式
簡介
AMD
原型模式
設計模式的分類
觀察者模式
命名空間模式
代理模式
編寫設計模式
適配器模式
反模式
什么是設計模式
模塊化模式
MVC
Mixin 模式
裝飾模式
設計模式的結(jié)構(gòu)
單例模式
迭代器模式
命令模式
工廠模式
MVP
暴露模塊模式
惰性初始模式

適配器模式

適配器模式 將一個對象或者類的接口翻譯成某個指定的系統(tǒng)可以使用的另外一個接口。

適配器基本上允許本來由于接口不兼容而不能一起正常工作的對象或者類能夠在一起工作.適配器將對它接口的調(diào)用翻譯成對原始接口的調(diào)用,而實現(xiàn)這樣功能的代碼通常是最簡的。

我們可能已經(jīng)用過的一個適配器的例子就是jQuery的jQuery.fn.css()方法,這個方法幫助規(guī)范了不同瀏覽器之間樣式的應用方式,使我們使用簡單的語法,這些語法被適配成為瀏覽器背后真正支持的語法:

// Cross browser opacity:
// opacity: 0.9;  Chrome 4+, FF2+, Saf3.1+, Opera 9+, IE9, iOS 3.2+, Android 2.1+
// filter: alpha(opacity=90);  IE6-IE8

// Setting opacity
$( ".container" ).css( { opacity: .5 } );

// Getting opacity
var currentOpacity = $( ".container" ).css('opacity');

將上面的代碼變得可行的相應的jQuery核心css鉤子在下面:

get: function( elem, computed ) {
  // IE uses filters for opacity
  return ropacity.test( (
        computed && elem.currentStyle ?
            elem.currentStyle.filter : elem.style.filter) || "" ) ?
    ( parseFloat( RegExp.$1 ) / 100 ) + "" :
    computed ? "1" : "";
},

set: function( elem, value ) {
  var style = elem.style,
    currentStyle = elem.currentStyle,
    opacity = jQuery.isNumeric( value ) ?
          "alpha(opacity=" + value * 100 + ")" : "",
    filter = currentStyle && currentStyle.filter || style.filter || "";

  // IE has trouble with opacity if it does not have layout
  // Force it by setting the zoom level
  style.zoom = 1;

  // if setting opacity to 1, and no other filters
  //exist - attempt to remove filter attribute #6652
  if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {

    // Setting style.filter to null, "" & " " still leave
    // "filter:" in the cssText if "filter:" is present at all,
    // clearType is disabled, we want to avoid this style.removeAttribute
    // is IE Only, but so apparently is this code path...
    style.removeAttribute( "filter" );

    // if there there is no filter style applied in a css rule, we are done
    if ( currentStyle && !currentStyle.filter ) {
      return;
    }
  }

  // otherwise, set new filter values
  style.filter = ralpha.test( filter ) ?
    filter.replace( ralpha, opacity ) :
    filter + " " + opacity;
}
};
上一篇:AMD下一篇:設計模式的分類