Java 之23种设计模式解析

B、结构模式(7种)

 

我们接着讨论设计模式,上篇文章我讲完了5种创建型模式,这章开始,我将讲下7种结构型模式:适配器模式、装饰模式、代理模式、外观模式、桥接模式、组合模式、享元模式。其中对象的适配器模式是各种模式的起源,我们看下面的图:

6、适配器模式

 适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。

01、类的适配器模式

核心思想就是:有一个Source类,拥有一个方法,待适配,目标接口是Targetable,通过Adapter类,将Source的功能扩展到Targetable里,看代码:

[java] view plaincopy

  1. public class Source {  
  2.   
  3.     public void method1() {  
  4.         System.out.println("this is original method!");  
  5.     }  
  6. }  

[java] view plaincopy

  1. public interface Targetable {  
  2.   
  3.     /* 与原类中的方法相同 */  
  4.     public void method1();  
  5.   
  6.     /* 新类的方法 */  
  7.     public void method2();  
  8. }  

[java] view plaincopy

  1. public class Adapter extends Source implements Targetable {  
  2.   
  3.     @Override  
  4.     public void method2() {  
  5.         System.out.println("this is the targetable method!");  
  6.     }  
  7. }  

Adapter类继承Source类,实现Targetable接口,下面是测试类:

[java] view plaincopy

  1. public class AdapterTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Targetable target = new Adapter();  
  5.         target.method1();  
  6.         target.method2();  
  7.     }  
  8. }  

输出:

this is original method!
this is the targetable method!

这样Targetable接口的实现类就具有了Source类的功能。

 

本教程由尚硅谷教育大数据研究院出品,如需转载请注明来源。

 

猜你喜欢

转载自blog.csdn.net/sggtgfs/article/details/82834415