State Design Pattern to design a Music System in C++ language.
#include<iostream>
using namespace std;
//current_context class
class State;
class MusicSystem
{
private:
State *currentState;
public:
MusicSystem();
void stopMusic();
void playMusic();
void playNextTrack();
void playPreviousTrack();
void setCurrentContext(State* s)
{
currentState=s;
}
};
//abstract state class
class State
{
public:
virtual void offState(MusicSystem *ms){cout<<"Already Stopped"<<endl;}
virtual void onState(MusicSystem* ms){cout<<"Already Playing"<<endl;}
virtual void playNextTrack(MusicSystem* ms){cout<<"Can not play Next in off state."<<endl;}
virtual void playPreviousTrack(MusicSystem* ms){cout<<"Can not play Previous in off state."<<endl;}
};
//concrete state class on
class OFF:public State
{
public:
void onState(MusicSystem *ms);
};
//concrete state class off
class ON:public State
{
public:
void offState(MusicSystem *ms);
void playNextTrack(MusicSystem *ms);
void playPreviousTrack(MusicSystem *ms);
};
MusicSystem::MusicSystem()
{
currentState=new OFF;
}
void MusicSystem::stopMusic()
{
currentState->offState(this);
}
void MusicSystem::playMusic()
{
currentState->onState(this);
}
void MusicSystem::playNextTrack()
{
currentState->playNextTrack(this);
}
void MusicSystem::playPreviousTrack()
{
currentState->playPreviousTrack(this);
}
void OFF::onState(MusicSystem *ms)
{
cout<<"Turning from stopped to Play."<<endl;
ms->setCurrentContext(new ON());
delete this;
}
void ON::offState(MusicSystem *ms)
{
cout<<"Turning from Playing to Stopped."<<endl;
ms->setCurrentContext(new OFF());
delete this;
}
void ON::playNextTrack(MusicSystem *ms)
{
cout<<"Playing next track..."<<endl;
//ms->setCurrentContext(new OFF());
//delete this;
}
void ON::playPreviousTrack(MusicSystem *ms)
{
cout<<"Playing previous track..."<<endl;
//ms->setCurrentContext(new OFF());
//delete this;
}
//main
int main()
{
MusicSystem ms;
ms.MusicSystem::stopMusic();
ms.MusicSystem::stopMusic();
ms.MusicSystem::stopMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();
ms.MusicSystem::playMusic();
ms.MusicSystem::playMusic();
ms.MusicSystem::playMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();
ms.MusicSystem::stopMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();
return 0;
}
No comments:
Post a Comment