设计模式--适配器模式

    适配器模式属于结构型模式
    基本原理:根据不同的需求,使用一个适配器去寻找应对的方法。
    主要流程:
            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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值