转换接口,在java中无法使用多重继承,所以只有对象适配器,而c++不仅有对象适配器,还有类适配器。
代码比较简单,火鸡的接口转化为鸭子。
#include <iostream>
using namespace std;
class Duck
{
public:
virtual void display() { }
void swim()
{
cout << "All ducks float, even decoys!" << endl;
}
virtual void fly()
{
cout << "I'm flying" << endl;
}
virtual void quack()
{
cout << "Quack"<<endl;
}
};
class MallardDuck : public Duck
{
public:
MallardDuck() { }
virtual void display()
{
cout << "I'm a real Mallard duck" << endl;
}
};
class Turkey
{
public:
virtual void gobble() { }
virtual void fly() { }
};
class WildTurkey : public Turkey
{
public:
virtual void gobble()
{
cout << "Gobble gobble" << endl;
}
virtual void fly()
{
cout << "I'm flying a short distance" << endl;
}
};
class TurkeyAdapter : public Duck
{
public:
Turkey* turkey;
TurkeyAdapter(Turkey* turkey)
{
this->turkey = turkey;
}
virtual void quack()
{
turkey->gobble();
}
virtual void fly()
{
for(int i = 0; i < 5; i++)
turkey->fly();
}
};
void testDuck(Duck* duck)
{
duck->quack();
duck->fly();
}
int main()
{
MallardDuck* duck = new MallardDuck();
WildTurkey* turkey = new WildTurkey();
Duck* turkeyAdapter = new TurkeyAdapter(turkey);
cout << "The turkey says ..." << endl;
turkey->gobble();
turkey->fly();
cout << "The Duck says ..."<< endl;
testDuck(duck);
cout << "The TurkeyAdapter says..."<< endl;
testDuck(turkeyAdapter);
return 0;
}