适配器模式定义:将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。
主要解决:在软件系统中,常常要将一些"现存的对象"放到新的环境中,而新环境要求的接口是现对象不能满足的。
解决方案:继承或依赖(推荐)。
优点:
1、可以让任何两个没有关联的类一起运行。
2、提高了类的复用。
3、增加了类的透明度。
4、灵活性好。
缺点:
1、过多地使用适配器,会让系统非常零乱,不易整体进行把握。比如,明明看到调用的是 A 接口,其实内部被适配成了 B 接口的实现,一个系统如果太多出现这种情况,无异于一场灾难。因此如果不是很有必要,可以不使用适配器,而是直接对系统进行重构。
2.由于 JAVA 至多继承一个类,所以至多只能适配一个适配者类,而且目标类必须是抽象类。
适配器模式类图:
代码实现:
客户端代码:
using System; namespace _01适配器模式_第一版 { class Program { static void Main(string[] args) { Target target = new Adapter(); target.Request(); Console.Read(); } } }
目标抽象类:
using System; using System.Collections.Generic; using System.Text; namespace _01适配器模式_第一版 { class Target { public virtual void Request() { Console.WriteLine("普通请求!"); } } }
适配器类:
using System; using System.Collections.Generic; using System.Text; namespace _01适配器模式_第一版 { class Adapter:Target { private Adaptee adaptee = new Adaptee(); public override void Request() { base.Request(); { adaptee.SpecificRequest(); } } } }
适配者类:
using System; using System.Collections.Generic; using System.Text; namespace _01适配器模式_第一版 { class Adaptee { public void SpecificRequest() { Console.WriteLine("特殊请求!"); } } }
总结:
适配器的三种模式:https://www.cnblogs.com/mingmingcome/p/9810731.html(推荐链接)
