为什么使用适配器?
①现有已测试过的代码,重复利用这些代码适配新的类会很方便;
②版本更新,通过适配器兼容旧版本。
三种对象:
①Adapter:适配器;
②Adaptee:被适配的类;
③Target:适配目标。
两种适配方式:
①Target为接口,Adaptee为类:继承Adaptee,实现接口
扫描二维码关注公众号,回复:
2038995 查看本文章
interface Target
{
public void TargetMethod();
}
class Adaptee
{
public void MethodA()
{
}
}
class Adapter : Adaptee,Target
{
public void TargetMethod()
{
MethodA();
}
}
②Target和Adaptee皆为类:继承Target,创建Adaptee的实例:
abstract class Target
{
public void TargetMethod()
{
}
}
class Adaptee
{
public void MethodA()
{
}
}
class Adapter : Target
{
private Adaptee adaptee;
public void TargetMethod()
{
adaptee.MethodA();
}
}
简单地随便写了下,大概就是这个意思。