场景:系统的数据和行为都正确,但是接口不符时,可以考虑适配器模式。适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境要求不一致。
结构图:
ay:适配的提供的接口和用户希望的接口一致。
效果图:
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StrategyMo { public class WinformWindow { public void GetWinformWindow() { Console.WriteLine("老window窗体"); } } public class Adapter : CustomNeed { WinformWindow winform = new WinformWindow(); public override void GetWpfHostWindow() { Console.WriteLine("适配额外的处理,把窗体适配,能在WPF中显示"); winform.GetWinformWindow(); } } public class CustomNeed { public virtual void GetWpfHostWindow() { Console.WriteLine("window窗体"); } } }
客户端使用:
CustomNeed cn = new Adapter(); cn.GetWpfHostWindow();
关于适配器模式和代理模式的区别:
你只要想到2个例子: 适配器,比如电源,中国220V,外国110V,中国的电源到外国就不能用了,你就需要个电源适配器了。用来适配电源的电压。
而代理,你想一下,假如你卖个东西,你把东西给代理商帮你卖,你们卖的是一样的东西,他销售出去,也等于你卖出去了。
代理的实现是,1个接口,多个对象实现。其中有个代理,代理中放个你,构造函数把你实例化,代理调用方法,等于中转一下调了你的方法,发货是从你这发的。