Skip to content

Instantly share code, notes, and snippets.

@yknishidate
Created March 6, 2022 13:33
Show Gist options
  • Save yknishidate/7382bf530970542eeb820a86dc73a0e0 to your computer and use it in GitHub Desktop.
Save yknishidate/7382bf530970542eeb820a86dc73a0e0 to your computer and use it in GitHub Desktop.
#include <iostream>
class Audio
{
public:
virtual ~Audio() {}
virtual void playSound(int soundId) = 0;
virtual void stopSound(int soundId) = 0;
};
class ConsoleAudio : public Audio
{
public:
void playSound(int soundId) override
{
std::cout << "ConsoleAudio::playSound()" << std::endl;
}
void stopSound(int soundId) override
{
std::cout << "ConsoleAudio::stopSound()" << std::endl;
}
};
class NullAudio : public Audio
{
public:
void playSound(int soundId) override
{
std::cout << "NullAudio::playSound()" << std::endl;
}
void stopSound(int soundId) override
{
std::cout << "NullAudio::stopSound()" << std::endl;
}
};
class Locater
{
public:
static void initialize()
{
m_service = &m_nullAudio;
}
static Audio &getAudio()
{
return *m_service;
}
static void provide(Audio *service)
{
m_service = service;
}
private:
static Audio *m_service;
static NullAudio m_nullAudio;
};
Audio *Locater::m_service;
NullAudio Locater::m_nullAudio;
int main()
{
Locater::initialize();
// before providing
{
Audio &audio = Locater::getAudio();
audio.playSound(0); // NullAudio::playSound()
}
ConsoleAudio *consoleAudio = new ConsoleAudio();
Locater::provide(consoleAudio);
Audio &audio = Locater::getAudio();
audio.playSound(0); // ConsoleAudio::playSound()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment