架构师_设计模式_结构型_适配器
适配器模式:两个不同的对象 让他们实现适配,
使用条件:第三方类是无法更改的才需要新增一层适配 可以更改就无须使用适配
有两种实现方法1: 以继承类方式适配,但是强耦合 子类继承了父类全部方法 可能是不需要的 2:组合方式进行适配
如果姚明会英语那么久没必要适配器,所以第三方内部可以更改就没必要适配器模式
适用于,我们自己已经定义好的类, 突然要对接第三方类(无法更改),
using System; namespace 适配器模式 { //适配器实现方式有两种 //第一种:以继承类方式适配,但是强耦合 子类继承了父类全部方法 可能是不需要的 //第二种:对象适配, 组合方式进行适配 class Program { static void Main(string[] args) { IHelp sqlhelp = new SqlHelp(); sqlhelp.ADD<string>(); IHelp oraclehelp = new OracleHelp(); oraclehelp.Delete<string>(); //第一种: 以继承类方式适配 IHelp redisHelp = new redisHelpAdapter(); oraclehelp.Delete<string>(); //第二种:对象组合,实现适配 IHelp redisHelpCombination = new redisHelpCombination(new RdeisHelp()); oraclehelp.Delete<string>(); Console.WriteLine("Hello World!"); } } public interface IHelp { public void ADD<T>(); public void Delete<T>(); public void Insert<T>(); public void Update<T>(); } public class SqlHelp : IHelp { public void ADD<T>() { throw new NotImplementedException(); } public void Delete<T>() { throw new NotImplementedException(); } public void Insert<T>() { throw new NotImplementedException(); } public void Update<T>() { throw new NotImplementedException(); } } public class OracleHelp : IHelp { public void ADD<T>() { throw new NotImplementedException(); } public void Delete<T>() { throw new NotImplementedException(); } public void Insert<T>() { throw new NotImplementedException(); } public void Update<T>() { throw new NotImplementedException(); } } //第三方help 但是里面的方法我们没有办法更改, //实现第一种方式,类继承适配 public class RdeisHelp { public void redisAdd<T>() { } } //创造适配器 public class redisHelpAdapter : RdeisHelp, IHelp { public void ADD<T>() { base.redisAdd<T>(); } public void Delete<T>() { throw new NotImplementedException(); } public void Insert<T>() { throw new NotImplementedException(); } public void Update<T>() { throw new NotImplementedException(); } } #region 第二种方法组合 public class redisHelpCombination : IHelp { private RdeisHelp _rdeisHelp = null; public redisHelpCombination(RdeisHelp rdeisHelp) { this._rdeisHelp = rdeisHelp; } public void ADD<T>() { throw new NotImplementedException(); } public void Delete<T>() { throw new NotImplementedException(); } public void Insert<T>() { throw new NotImplementedException(); } public void Update<T>() { throw new NotImplementedException(); } } #endregion }
本文来自博客园,作者:12不懂3,转载请注明原文链接:https://www.cnblogs.com/LZXX/p/12882560.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY