适配器模式的意图就是将一个接口转化为客户需要的接口请求。例如已经存在某方法ClassA.MakeMyLine(Args),很确定的是这个类以及很
成熟,我们在开发ClassB的时候,需要调用该方法,但是ClassB的接口设计师MakeLine(Args)而不是
MakeMyLine(Args),这就需要一种中间的转化:
using System;
using System.Text ;
public class TestAdapter{
public static void Main() {
Target Myobj=new Adapter(new Adaptee());
Myobj.Execute("参数");
}
};
public abstract class Target{
public abstract void Execute(string args);
};
public class Adapter:Target{
public override void Execute(string args){
this.MyAdaptee.MyExecute(args);
}
private Adaptee MyAdaptee;
public Adapter(Adaptee obj){
this.MyAdaptee= obj;
}
};
public class Adaptee{
public void MyExecute(string args){
Console.WriteLine("执行实际方法Adaptee.MyExecute({0})",args);
}
};
using System.Text ;
public class TestAdapter{
public static void Main() {
Target Myobj=new Adapter(new Adaptee());
Myobj.Execute("参数");
}
};
public abstract class Target{
public abstract void Execute(string args);
};
public class Adapter:Target{
public override void Execute(string args){
this.MyAdaptee.MyExecute(args);
}
private Adaptee MyAdaptee;
public Adapter(Adaptee obj){
this.MyAdaptee= obj;
}
};
public class Adaptee{
public void MyExecute(string args){
Console.WriteLine("执行实际方法Adaptee.MyExecute({0})",args);
}
};
这是公开一个虚类的方法,在使用的过程中为了适配该方法,同时又调用其他类的其他方法,而做的适配器模式代码。
这里的Target类我做成了abstract class,在实际中,也有可能是
public interface Target{
void Execute(string args);
};
void Execute(string args);
};
这种模式的,相应的
public void Execute(string args)
这个方法不再是override的了。
实际中,这个模式的用户非常广泛,例如在播放器MPC中,是典型的。