前言:【模式總覽】——————————by xingoohtml
若是已經有了一種類,而須要調用的接口卻並不能經過這個類實現。所以,把這個現有的類,通過適配,轉換成支持接口的類。編程
換句話說,就是把一種現有的接口編程另外一種可用的接口。設計模式
【類的適配器】this
Target 目標接口spa
Adaptee 現有的類設計
Adapter 中間轉換的類,即實現了目標接口,又繼承了現有的類。code
1 package com.xingoo.test1; 2 interface Target{ 3 public void operation1(); 4 public void operation2(); 5 } 6 class Adaptee{ 7 public void operation1(){ 8 System.out.println("operation1"); 9 } 10 } 11 12 class Adapter extends Adaptee implements Target{ 13 public void operation2() { 14 System.out.println("operation2"); 15 } 16 } 17 18 public class test { 19 public static void main(String[] args){ 20 Target tar = new Adapter(); 21 tar.operation1(); 22 tar.operation2(); 23 } 24 }
【對象的適配器】htm
與上面不一樣的是,此次並非直接繼承現有的類,而是把現有的類,做爲一個內部的對象,進行調用。對象
1 package com.xingoo.test2; 2 3 interface Target{ 4 public void operation1(); 5 public void operation2(); 6 } 7 8 class Adaptee{ 9 public void operation1(){ 10 System.out.println("operation1"); 11 } 12 } 13 14 class Adapter implements Target{ 15 private Adaptee adaptee; 16 public Adapter(Adaptee adaptee){ 17 this.adaptee = adaptee; 18 } 19 public void operation1() { 20 adaptee.operation1(); 21 } 22 23 public void operation2() { 24 System.out.println("operation2"); 25 } 26 27 } 28 public class test { 29 public static void main(String[] args){ 30 Target tar = new Adapter(new Adaptee()); 31 tar.operation1(); 32 tar.operation2(); 33 } 34 }
1 想使用一個已經存在的類,可是它的接口並不符合要求blog
2 想建立一個能夠複用的類,這個類與其餘的類能夠協同工做
3 想使用已經存在的子類,可是不可能對每一個子類都匹配他們的接口。所以對象適配器能夠適配它的父類接口。(這個沒理解,之後慢慢琢磨)
俗話說,窈窕淑女君子好逑,最近看跑男,十分迷戀Baby。
可是,若是桃花運淺,身邊只有鳳姐,那麼也不須要擔憂。
只須要簡單的化妝化妝,PS一下,美女鳳姐,依然無可替代!
雖然,沒有AngleBaby,可是咱們有鳳姐,因此依然能夠看到AngleBaby甜美的笑。
1 package com.xingoo.test3; 2 interface BeautifulGirl{ 3 public void Smiling(); 4 } 5 class UglyGirl{ 6 public void Crying(){ 7 System.out.println("我在哭泣..."); 8 } 9 } 10 class ApplyCosmetics implements BeautifulGirl{ 11 private UglyGirl girl; 12 public ApplyCosmetics(UglyGirl girl){ 13 this.girl = girl; 14 } 15 public void Smiling() { 16 girl.Crying(); 17 } 18 } 19 public class test { 20 public static void main(String[] args){ 21 BeautifulGirl girl = new ApplyCosmetics(new UglyGirl()); 22 girl.Smiling(); 23 } 24 }
運行結果
我在哭泣...