生成一段Cplus程序,实现使用适配器模式,对网口和PCIE接口的通信接口进行封装
时间: 2024-05-30 13:14:34 浏览: 107
好的,以下是使用适配器模式对网口和PCIE接口的通信接口进行封装的C++程序:
#include <iostream>
using namespace std;
// 接口类,网口和PCIE接口的通信接口都实现该接口
class Communication {
public:
virtual void send() = 0; // 发送数据方法
virtual void receive() = 0; // 接收数据方法
};
// 网口通信类
class EthernetCommunication : public Communication {
public:
void send() {
cout << "使用网口发送数据" << endl;
}
void receive() {
cout << "使用网口接收数据" << endl;
}
};
// PCIE通信类
class PcieCommunication : public Communication {
public:
void send() {
cout << "使用PCIE接口发送数据" << endl;
}
void receive() {
cout << "使用PCIE接口接收数据" << endl;
}
};
// 适配器类,将网口和PCIE接口的通信接口适配为统一的通信接口
class CommunicationAdapter : public Communication {
private:
Communication* communication;
public:
CommunicationAdapter(Communication* comm) {
communication = comm;
}
void send() {
communication->send();
}
void receive() {
communication->receive();
}
};
int main() {
// 网口通信
EthernetCommunication* ethComm = new EthernetCommunication();
CommunicationAdapter* adapter1 = new CommunicationAdapter(ethComm);
adapter1->send();
adapter1->receive();
// PCIE通信
PcieCommunication* pcieComm = new PcieCommunication();
CommunicationAdapter* adapter2 = new CommunicationAdapter(pcieComm);
adapter2->send();
adapter2->receive();
delete ethComm;
delete adapter1;
delete pcieComm;
delete adapter2;
return 0;
}
阅读全文