適配器模式把一個類的接口變換成客戶端所期待的另一種接口,從而使原本接口不匹配而無法在一起工作的兩個類能夠在一起工作。
二,類的Adapter模式的結構:
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
三,示例代碼
/**
* 目標
*
* @author Salmon
*
*/
public interface Target {
public void request();
}
/**
* 源
*
* @author Salmon
*
*/
public class Adaptee {
public void specificRequest() {
System.out.println("Called SpecificRequest()");
}
}
/**
* 適配器
*
* @author Salmon
*
*/
public class Adapter extends Adaptee implements Target {
// Implements ITarget interface
public void request() {
// Possibly do some data manipulation
// and then call SpecificRequest
this.specificRequest();
}
}
/**
* 客戶代碼
*
* @author Salmon
*
*/
public class Client {
public static void Main(String[] args) {
// Create adapter and place a request
Target t = new Adapter();
t.request();
}
}
四,對象的Adapter模式的結構
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
目標(Target)角色:
這是客戶所期待的接口。目標可以是具體的或抽象的類,也可以是接口。
源(Adaptee)角色:
需要適配的類。
適配器(Adapter)角色:
通過在內部包裝(Wrap)一個Adaptee對象,把源接口轉換成目標接口。
五,示例代碼
/**
* 目標接口
* @author Salmon
*
*/
public interface Target {
public void request();
}
/**
* 源
* @author Salmon
*
*/
public class Adaptee {
public void SpecificRequest() {
System.out.println("Called SpecificRequest()");
}
}
/**
* 適配器
* @author Salmon
*
*/
public class Adapter implements Target {
private Adaptee adaptee = new Adaptee();
public void request() {
// Possibly do some data manipulation
// and then call SpecificRequest
adaptee.SpecificRequest();
}
}
/**
* 客戶端代碼
*
* @author Salmon
*
*/
public class Client {
public static void main(String[] args) {
// Create adapter and place a request
Target t = new Adapter();
t.request();
}
}
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

