适配器模式

转换接口,在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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值