定义:将一个类的一组接口变换成客户端所期待的另一种接口,从而使因接口不匹配而无法在一起工作的两个类能够在一起工作。类适配器通过集成被适配类和目标类,对象适配器通过组合来适配被适配者。
UML类图:
C++实现:
#include<iostream>
using namespace std;
class Duck
{
public:
virtual void Quack() = 0;
virtual void fly() = 0;
virtual ~Duck() = default;
};
class Turkey
{
public:
virtual void gobble() = 0;
virtual void fly() = 0;
virtual ~Turkey() = default;
};
class TurkeyAdapter :public Duck
{
public:
Turkey* turkey;
TurkeyAdapter(Turkey* turkey)
{
this->turkey = turkey;
}
void Quack()
{
turkey->gobble();
}
void fly()
{
for (int i = 0; i < 5; ++i)
turkey->fly();
}
virtual ~TurkeyAdapter() {}
};
class Lty :public Duck
{
// 通过 Duck 继承
virtual void Quack() override
{
cout << "GUA GUA GUA!" << endl;
}
virtual void fly() override
{
cout << "I can fly 5m!" << endl;
}
virtual ~Lty() {}
};
class Hj :public Turkey
{
// 通过 Turkey 继承
virtual void gobble() override
{
cout << "GU GU GU!" << endl;
}
virtual void fly() override
{
cout << "I can fly 1m!" << endl;
}
virtual ~Hj() {}
};
class Context
{
public:
Duck* duck;
Context(Duck* duck)
{
this->duck = duck;
}
void Jiao()
{
duck->Quack();
}
void Fei()
{
duck->fly();
}
~Context(){}
};
int main()
{
Lty* lty = new Lty();
Hj* hjj = new Hj();
TurkeyAdapter* ta = new TurkeyAdapter(hjj);
Context* context = new Context(ta);
context->Jiao();
context->Fei();
delete context;
context = new Context(lty);
context->Jiao();
context->Fei();
return 0;
}
C#实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace ConsoleApp1
{
public interface Duck
{
void Quack();
void fly();
}
public interface Turkey
{
void gobble();
void fly();
}
public class TurkeyAdapter : Duck
{
Turkey turkey;
public TurkeyAdapter(Turkey turkey)
{
this.turkey = turkey;
}
void Duck.Quack()
{
turkey.gobble();
}
void Duck.fly()
{
for(int i=0;i<5;++i)
turkey.fly();
}
}
public class Lty : Duck
{
public void fly()
{
WriteLine("yz fly 5m");
}
public void Quack()
{
WriteLine("yzzzzz");
}
}
public class HJJ : Turkey
{
public void fly()
{
WriteLine("hjf 1m");
}
public void gobble()
{
WriteLine("hjjjjjjj");
}
}
public class Context
{
Duck duck;
public Context(Duck duck)
{
this.duck = duck;
}
public void Jiao()
{
this.duck.Quack();
}
public void Fei()
{
this.duck.fly();
}
}
class Program
{
static void Main(string[] args)
{
Lty lty = new Lty();
HJJ hj = new HJJ();
TurkeyAdapter ta = new TurkeyAdapter(hj);
Context context = new Context(ta);
context.Jiao();
context.Fei();
context = new Context(lty);
context.Jiao();
context.Fei();
}
}
}