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

时间:2022-04-22
本文章向大家介绍【设计模式】—— 适配器模式Adapter,主要内容包括模式意图、模式结构、使用场景、生活中的设计模式、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

  模式意图

  如果已经有了一种类,而需要调用的接口却并不能通过这个类实现。因此,把这个现有的类,经过适配,转换成支持接口的类。

  换句话说,就是把一种现有的接口编程另一种可用的接口。

  模式结构

  【类的适配器】

  Target 目标接口

  Adaptee 现有的类

  Adapter 中间转换的类,即实现了目标接口,又继承了现有的类。

 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 }

  【对象的适配器】

  与上面不同的是,这次并不是直接继承现有的类,而是把现有的类,作为一个内部的对象,进行调用。

 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 想使用一个已经存在的类,但是它的接口并不符合要求

  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 }

  运行结果

我在哭泣...