设计模式(五)——适配器模式

1.描述

将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口比兼容而不能一起工作的那些类可以一起工作。

2.优点

·目标(Target)与被适配者(Adaptee)是完全解耦关系。

·满足“开闭原则”

3.使用情景

一个程序想使用已存在的类,但该类所实现的接口和当前程序所使用的接口不一致。

4.模式的使用

·目标(Target):目标是一个接口,该接口是客户想使用的接口。

·被适配者(Adapter):被适配者是一个已存在的接口或抽象类,这个接口或抽象类需要适配。

·适配器(Adapter):适配器是一个类,该类实现了目标接口并包含有被适配者的引用,即适配器的职责是对被适配者接口(抽象类)与目标接口进行适配。

5.UML图

6.案例

演示如何使用该模式:

 1 package 适配器模式;
 2 
 3 public class test1 {
 4     public static void main(String[] args) {
 5         A a = new AClass();
 6         a.method();
 7         A aoa = new AdpterOfA(new BClass());
 8         aoa.method();
 9     }
10 
11 }
12 
13 /*
14  * 目标
15  */
16 interface A{ public abstract void method();}
17 
18 /*
19  * 被适配者
20  */
21 interface B{ public abstract void method();}
22 
23 /*
24  * 适配器
25  */
26 class AdpterOfA implements A{
27     B b;
28     AdpterOfA(B b){
29         this.b = b; 
30     }
31     public void method(){
32         b.method();
33     }
34 }
35 
36 class AClass implements A{
37     public void method(){
38         System.out.println("A类实现了接口" + this.getClass().getInterfaces()[0]);
39     }
40 }
41 
42 class BClass implements B{
43     public void method(){
44         System.out.println("B 类实现了接口" + this.getClass().getInterfaces()[0]);
45     }
46 }

 需要重写被适配者中需要的方法,我觉得在需要重写的方法很多时这是十分麻烦的,我在找找看有没有更简便的方法重写被适配者中的方法。

原文地址:https://www.cnblogs.com/cxy2016/p/7586641.html