适配器模式属于结构型模式
基本原理:根据不同的需求,使用一个适配器去寻找应对的方法。
主要流程:
1.创建解决方法的类。
2.创建一个适配器,根据不同需求对应相应的解决方法。
3.使用一个类去分配适配器。
注意:适配器不是在详细设计时添加的,而是解决正在服役的项目的问题。
#include <iostream>
#include <string>
using namespace std;
//创建需要适配的种类
class AdvanceMediaPlayer
{
public:
virtual void playVlc(string fileName) = 0;
virtual void playMp4(string fileName) = 0;
};
class VlcPlayer : public AdvanceMediaPlayer
{
public:
void playVlc(string fileName)
{
cout<<"playing vlc file. name is "<<fileName<<endl;
}
void playMp4(string fileName){}
};
class Mp4Player : public AdvanceMediaPlayer
{
public:
void playVlc(string fileName){}
void playMp4(string fileName)
{
cout<<"playing mp4 file. name is "<<fileName<<endl;
}
};
//创建适配器
class MediaPlayer
{
public:
virtual void play(string audioType,string fileName) = 0;
};
//适配器的派生类
class MediaAdapter:public MediaPlayer
{
private:
AdvanceMediaPlayer * advanceMediaPlayer;
public:
MediaAdapter(string audioType)
{
if(audioType == "vlc")
{
advanceMediaPlayer = new VlcPlayer();
}
else if(audioType == "mp4")
{
advanceMediaPlayer = new Mp4Player();
}
}
void play(string audioType,string fileName)
{
if(audioType == "vlc")
{
advanceMediaPlayer->playVlc(fileName);
}
else if(audioType == "mp4")
{
advanceMediaPlayer->playMp4(fileName);
}
}
};
//使用适配器的类
class AudioPlayer:public MediaPlayer
{
private:
MediaAdapter * mediaAdapter;
public:
void play(string audioType,string fileName)
{
if(audioType == "mp3")
{
cout<<"playing mp3 file. name is "<<fileName<<endl;
}
else if(audioType == "mp4" || audioType == "vlc")
{
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter->play(audioType,fileName);
}
else
{
cout<<"Invalid media. "<<audioType<<"format not supported"<<endl;
}
}
};
int main()
{
AudioPlayer *audioPlayer = new AudioPlayer();
audioPlayer->play("mp3","aaa.mp3");
audioPlayer->play("mp4","bbb.mp4");
audioPlayer->play("vlc","ccc.vlc");
audioPlayer->play("avi","ddd.avi");
return 0;
}