標籤:mini interface blank 資料 dap end alt com class
一、概述
概念
其實,舉個生活中的例子的話,適配器模式可以類比轉接頭,比如typeC和USB的轉接頭,把原本只能接typeC的介面,拓展為可以接普通USB;這裡的轉接頭一方面需要查在typeC上,一方面需要作為USB插口。
如果要舉個Java中的例子的話,不妨看看JDBC的章節介紹!為JDBC簡略UML圖(中間的xxx JDBC就是我們適配JDBC與各大資料庫廠商的適配器了!)
簡略圖
類的適配器模式
對象的適配器模式(注意看類的關係,上面是繼承,下面是委派)
二、實踐
上面提到的轉接頭的例子,我們參考:http://www.cnblogs.com/V1haoge/p/6479118.html
當然,此例和上述轉接頭的例子本質是一樣的(只是根據功能把介面分開的寫法)
類的適配,我們分別寫出簡略圖中的角色即可
目標角色
/** * 目標介面 * Administrator * 日期: 2017/10/28 **/public interface Target { /** * 目標操作1 */ void operation1(); /** * 目標操作2 */ void operation2();}
源角色
/** * 源角色 * Administrator * 日期: 2017/10/28 **/public class Adaptee { public void operation1(){ System.out.println("adaptee#opetion1()"); }}
適配器
/** * 適配器角色 * Administrator * 日期: 2017/10/28 **/public class Adapter extends Adaptee implements Target{ @Override public void operation2() { System.out.println("adapter#operation2()"); }}
用戶端使用
public class Client { public static void main(String[] args) { Target t = new Adapter(); t.operation2(); }}
對象的適配器我們看核心的適配器角色
適配器
/** * 適配器角色 * Administrator * 日期: 2017/10/28 **/public class Adapter implements Target{ private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } @Override public void operation1() { adaptee.operation1(); } @Override public void operation2() { System.out.println("adapter#operation2()"); }}
Java設計模式(7)——結構型模式之適配器模式