• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
戈瑾
博客园    首页    新随笔    联系   管理    订阅  订阅
适配器模式——C++实现

问题描述:

实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。

类图:

 

 

 

C++代码:

 

#include<iostream>
using namespace std;
class Cat{
public:
	virtual void cry()=0;
	virtual void zhua()=0;
};
class Dog{
public:
	virtual void wang()=0;
	virtual void run()=0;
};
class RealCat:public Cat{
public:
	void cry(){
		cout<<"喵喵叫!"<<endl;
	}
	void zhua(){
		cout<<"抓老鼠!"<<endl;
	}
};
class RealDog:public Dog{
public:
	void wang(){
		cout<<"汪汪叫!"<<endl;
	}
	void run(){
		cout<<"快快跑!"<<endl;
	}
};
class Adapter:public Cat,public Dog{
private:
	static Cat *cat;
	static Dog *dog;
public:
	void setCat(Cat *c){
		cat=c;
	}
	void setDog(Dog *d){
		dog=d;
	}
	void wang(){
	}
	void zhua(){
	}
	void run(){
		cout<<"小狗学小猫!"<<endl;
		cat->zhua();
	}
	void cry(){
		cout<<"小猫学小狗:"<<endl;
		dog->wang();
	}
};
Cat* Adapter::cat=new RealCat();
Dog* Adapter::dog=new RealDog();
int main(){
	Adapter adapter;
	adapter.run();
	adapter.cry();
	return 0;
}

  

运行结果:

 

posted on 2021-10-02 11:26  戈瑾  阅读(168)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3