对象适配器是对象的合成关系,也可以说是类的关联关系;
对象适配器,相比于类适配器,对象适配器是通过类间的关联关系进行耦合的,因此在设计时就可以做到比较灵活,实际项目中,使用的较多;
// 目标
class IMediaPlayer{
public:
virtual void play(string fileName) = 0;
};
// 源
class IAdvacneMediaPlayer{
public:
virtual void playVlc(string fileName) = 0;
virtual void playMp4(string fileName) = 0;
};
class VlcPlayer : public IAdvacneMediaPlayer{
public:
virtual void playVlc(string fileName){
cout << "playing vlc file: " << fileName << endl;
}
virtual void playMp4(string fileName){
}
};
class Mp4Player : public IAdvacneMediaPlayer{
public:
virtual void playVlc(string fileName){
}
virtual void playMp4(string fileName){
cout << "playing mp4 file: " << fileName << endl;
}
};
// VLC 适配器
class VlcAudioMediaAdapter : public IMediaPlayer{
public:
VlcAudioMediaAdapter(VlcPlayer* player){
this->player = player;
}
virtual void play(string fileName){
player->playVlc(fileName);
}
private:
VlcPlayer* player;
};
// MP4 适配器
class Mp4AudioMediaAdapter : public IMediaPlayer{
public:
Mp4AudioMediaAdapter(Mp4Player* player){
this->player = player;
}
virtual void play(string fileName){
player->playMp4(fileName);
}
private:
Mp4Player* player;
};
int main(){
IMediaPlayer* media = new VlcAudioMediaAdapter(new VlcPlayer);
media->play("/home/a.vlc");
media = new Mp4AudioMediaAdapter(new Mp4Player);
media->play("/home/b.mp4");
return 0;
}