【设计模式】—— 适配器模式Adapter

  前言:【模式总览】——————————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 }

  运行结果

我在哭泣...
相关文章
相关标签/搜索