介面卡模式 詳解

2022-01-23 06:45:02 字數 1818 閱讀 6780

將乙個類轉換成客戶希望的另外乙個介面。adapter模式使得原本由於介面不相容而不能一起工作;

建立型模式

/**

* created by george on 16/7/2.

*/// 鴨子

var duck = function () {};

duck.prototype.fly = function () ;

duck.prototype.quack = function () ;

// 火雞

var turkey = function () {};

turkey.prototype.fly = function () ;

turkey.prototype.gobble = function () ;

//具體的鴨子

var mallardduck = function () ;

//原型

mallardduck.prototype = new duck();

mallardduck.prototype.fly = function () ;

mallardduck.prototype.quack = function () ;

// 具體火雞

var wildturkey = function () ;

//原型

wildturkey.prototype = new turkey();

wildturkey.prototype.fly = function () ;

wildturkey.prototype.gobble = function () ;

//為了讓火雞也能支援鴨子的quack方法

var turkeyadapter = function (oturkey) ;

turkeyadapter.prototype = new duck();

turkeyadapter.prototype.quack = function () ;

turkeyadapter.prototype.fly = function ()

};var omallardduck = new mallardduck();

var owildturkey = new wildturkey();

var oturkeyadapter = new turkeyadapter(owildturkey);

//原有的鴨子行為;

omallardduck.fly();

omallardduck.quack(); //鴨子叫

console.log("------------");

//原有的火雞行為

owildturkey.fly();

owildturkey.gobble(); //火雞叫

console.log("------------");

//介面卡火雞的行為

oturkeyadapter.fly();

oturkeyadapter.quack();

通過介面卡,客戶端可以呼叫同一介面,因而對客戶端來說是透明的;

復用了現存的類,解決了現存類和復用環境要求不一致的問題;

將目標類和適配者類解耦,通過引入乙個介面卡類重用現有的適配者類,而無需修改原有的**;

乙個物件介面卡可以把多個不同的適配者類適配到同乙個目標,也就是說,同乙個介面卡可以把適配者類和它的子類都適配到目標介面;

對於物件介面卡來說,更換介面卡的實現過程比較複雜;

介面卡模式 詳解

將乙個類轉換成客戶希望的另外乙個介面。adapter模式使得原本由於介面不相容而不能一起工作 建立型模式 created by george on 16 7 2.鴨子 var duck function duck.prototype.fly function duck.prototype.quack...

介面卡模式(類介面卡 物件介面卡)

做個筆記 引用 public inte ce usb public inte ce psp public class usber implements usb 類介面卡 psp適用usb介面 public class usbadapter extends usber implements psp 物...

介面卡模式 預設介面卡,類介面卡,物件介面卡

模式思想 改變乙個類的對外介面 增加或減少 以滿足不同外部呼叫者的需求 角色成員 目標介面 target 客戶所期待的介面。目標可以是具體的或抽象的類,也可以是介面。需要適配的類 adaptee 需要適配的類或適配者類。介面卡 adapter 通過包裝乙個需要適配的物件,把原介面轉換成目標介面。適配...