- 双向适配器模式:将一个类的接口适配成用户所期待的。一个适配允许通常因为接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
例子:
设计和实现一个双向适配器实例,使得猫Cat可以学狗Dog叫Cry() ,狗可以学猫抓老鼠CatchMouse() 。
类图:
namespace 双向适配器
{
class Program
{
static void Main(string[] args)
{
DogTarget dog = new ConcreteDog();
CatTarget cat = new ConcreteCat();
dog.Cry();
cat.CatchMouse();
Adapter adapter = new Adapter(dog,cat);
adapter.CatchMouse();
adapter.Cry();
Console.ReadKey();
}
}
public interface DogTarget
{
void Cry();
}
public interface CatTarget
{
void CatchMouse();
}
public class ConcreteCat : CatTarget
{
public void CatchMouse()
{
Console.WriteLine("会抓老鼠!");
} }
public class ConcreteDog : DogTarget
{
public void Cry()
{
Console.WriteLine("汪汪汪..");
}}
public class Adapter:CatTarget,DogTarget
{
private CatTarget cat;
private DogTarget dog;
public Adapter(DogTarget dogtarget,CatTarget cattarget)
{
this.dog = dogtarget;
this.cat = cattarget;
}
public void Cry()
{cat.CatchMouse();
}
public void CatchMouse()
{
dog.Cry();
}
}
}
如有错误的地方还请指正!