适配器模式:两个不同的对象 让他们实现适配,
使用条件:第三方类是无法更改的才需要新增一层适配 可以更改就无须使用适配
有两种实现方法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 }