博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
适配器模式
阅读量:3942 次
发布时间:2019-05-24

本文共 1571 字,大约阅读时间需要 5 分钟。

适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口,Adapter模式使原来由于接口不兼容而不能一起工作的那些类可以一起工作。

什么时候使用适配器?

在想要使用一个已存在的类,但是如果它的接口,也就是它的方法和你的要求不相同的时候,就应该考虑使用适配器模式,两个类所做的事件相同或相似,但是具有不同的接口时要使用它

在这里插入图片描述

适配器模式在实现上就是利用一个类将接口不匹配的的接口重新封装一遍

#include 
#include
using namespace std;//class Player{
public: Player(){
} Player(string n):name(n){
} virtual void Attack() = 0; virtual void Defense() = 0;protected: string name;};//前锋class Forwards: public Player{
public: Forwards(string n):Player(n){
} void Attack() {
cout << name << " 前锋攻击 " << endl; } void Defense() {
cout << name << " 前锋防御 " << endl; }};//中锋class Center : public Player{
public: Center(string n):Player(n){
} void Attack() {
cout << name << " 中锋攻击 " << endl; } void Defense() {
cout << name << " 中锋防御 " << endl; }};//外籍运动员,chinaAttack,chinaDefences 接口不适用于Attack 与 Defences//但是两对接口的功能时类似的,//所以用适配器将接口转换一致,使得客户端的调用更加简单class ForeignCenter{
public: ForeignCenter(){
} ForeignCenter(string n):name(n){
} void chinaAttack(){
cout << name << " 外籍中锋攻击 " << endl; } void chinaDefences(){
cout << name << " 外籍中锋防御 " << endl; }protected: string name;};class Adapter : public Player{
public: Adapter(string n):foreign(new ForeignCenter(n)){
} void Attack() {
foreign->chinaAttack(); } void Defense() {
foreign->chinaDefences(); }private: ForeignCenter *foreign;};int main(){
Player *p1 = new Forwards("科比"); Player *p2 = new Center("乔丹"); Player *p3 = new Adapter("姚明"); p1->Attack(); p2->Attack(); p3->Attack(); p1->Defense(); p2->Defense(); p3->Defense(); return 0;}

转载地址:http://gxnwi.baihongyu.com/

你可能感兴趣的文章
CentOS 7系统上制作Clonezilla(再生龙)启动U盘并克隆双系统
查看>>
fail2ban的使用-控制连接数
查看>>
btkill-连接数控制
查看>>
dhcp.conf
查看>>
关于win10的升级
查看>>
cacti突然不显示流量
查看>>
发现一个好工具记录一下,U盘启动ISO文件。
查看>>
centos7下配置网卡以及查询网卡UUID
查看>>
适用于旧计算机的10款最佳轻量级Linux发行版
查看>>
在VMware Workstation中批量创建上千台虚拟机
查看>>
linux常用软件收集
查看>>
linux查看桌面环境
查看>>
centos8安装ntfs-3g后,不能自动挂载U盘(NTFS格式)
查看>>
Linux安装显卡驱动
查看>>
使用minicom
查看>>
linux常用外设-打印机指纹和蓝牙的安装管理
查看>>
记录一下安装在移动硬盘上的fedora linux v33在各种笔记本下的兼容性
查看>>
关于安装系统后不能启动的问题!
查看>>
U盘的挂载过程-先记录一下
查看>>
python程序启动过程报错的排错一般步骤
查看>>