惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
博客园 - 司徒正美
C
Check Point Blog
G
Google Developers Blog
The GitHub Blog
The GitHub Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
有赞技术团队
有赞技术团队
P
Proofpoint News Feed
IT之家
IT之家
B
Blog
博客园_首页
量子位
MongoDB | Blog
MongoDB | Blog
博客园 - Franky
J
Java Code Geeks
H
Help Net Security
A
About on SuperTechFans
Apple Machine Learning Research
Apple Machine Learning Research
Jina AI
Jina AI
D
DataBreaches.Net
Y
Y Combinator Blog
大猫的无限游戏
大猫的无限游戏
云风的 BLOG
云风的 BLOG
Google DeepMind News
Google DeepMind News

博客园 - 隴上煙雨劍

什么是交叉验证 一句话设计模式 代理模式 中介模式 桥接模式 吐槽一下依赖倒置这个糟糕的名字 设计模式之状态模式 设计模式之装饰器模式 mysql插入数据如果存在则忽略 自己手写一个js的双向绑定 Java已经不再是以前的java了 无法访问9200端口的ElasticSearch服务 Forbidden You don't have permission to access / on this server [转帖]快速激活最新JetBrains公司系列产品包括最新的phpstorm10 【转】CI去掉index.php VirtualBox在win8.1中无法安装64位虚拟机 多谢Mono Ubuntu14.04上面安装mono3.12版本 更新线上数据库时候的安全操作
适配器模式
隴上煙雨劍 · 2023-07-22 · via 博客园 - 隴上煙雨劍

适配器模式(Adapter Pattern)说白了就是把一个接口实现类转换成另外一个接口对象。先看代码:

 1 // 目标接口
 2 public interface ITarget
 3 {
 4     void Request();
 5 }
 6 
 7 // 原本不兼容的类
 8 public class Adaptee
 9 {
10     public void SpecificRequest()
11     {
12         Console.WriteLine("Adaptee's specific request.");
13     }
14 }
15 
16 // 适配器类
17 public class Adapter : ITarget
18 {
19     private readonly Adaptee adaptee;
20 
21     public Adapter(Adaptee adaptee)
22     {
23         this.adaptee = adaptee;
24     }
25 
26     public void Request()
27     {
28         // 通过适配器调用原本不兼容类的方法
29         adaptee.SpecificRequest();
30     }
31 }
32 
33 // 客户端代码
34 public class Client
35 {
36     public static void Main(string[] args)
37     {
38         Adaptee adaptee = new Adaptee();
39         ITarget target = new Adapter(adaptee);
40 
41         target.Request(); // 输出:"Adaptee's specific request."
42     }
43 }

八股:

适配器模式(Adapter Pattern)是一种结构型设计模式,它允许将一个类的接口转换成客户端期望的另一个接口,从而使得原本不兼容的类能够一起工作。适配器模式可以解决不同接口之间的兼容性问题,使得不需要修改现有代码就可以让多个类协同工作。

适配器模式中包含三种主要角色:

  1. 目标接口(Target):目标接口是客户端期望的接口,适配器类将原本不兼容的类转换成这个目标接口。

  2. 适配器类(Adapter):适配器类实现目标接口,并包含一个对原本不兼容类的引用,通过适配器类的方法调用原本不兼容类的方法,从而实现目标接口。

  3. 原本不兼容的类(Adaptee):原本不兼容的类是客户端需要使用的类,但它的接口与目标接口不兼容。

适配器模式的核心思想是通过适配器类将原本不兼容的类进行包装,使得它们能够在目标接口下工作。这样,客户端就可以通过目标接口来调用原本不兼容类的方法,而不需要关心实际的实现细节。