目录
- [【设计模式专题之适配器模式】6. 扩展坞](#【设计模式专题之适配器模式】6. 扩展坞)
【设计模式专题之适配器模式】6. 扩展坞
文章链接:卡码网设计模式
题目链接:6. 扩展坞
感觉原题和原题解不太能体现出适配器模式,自己改了一下代码。
cpp
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class USB{
public:
virtual void charge() = 0;
};
class TypeC{
public:
virtual void chargetypeC() = 0;
};
class USBAdapter : public USB{
private:
TypeC* typeC;
public:
USBAdapter(TypeC* typeC): typeC(typeC) {}
void charge() override{
typeC->chargetypeC();
}
};
class NewComputer : public TypeC{
public:
void chargetypeC() override{
cout << "TypeC" << endl;
}
};
int main(){
int N;
cin >> N;
for (int i = 0; i < N; i++){
int choice;
cin >> choice;
if (choice == 1){
TypeC* newcomputer = new NewComputer();
newcomputer->chargetypeC();
delete newcomputer;
}else if (choice == 2){
TypeC* newcomputer = new NewComputer();
USB* usbadapter = new USBAdapter(newcomputer);
usbadapter->charge();
delete newcomputer;
delete usbadapter;
}
}
return 0;
}
设计模式第四天,加油!!!