Skip to content

Instantly share code, notes, and snippets.

@nazgob
Created February 27, 2011 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nazgob/846263 to your computer and use it in GitHub Desktop.
Save nazgob/846263 to your computer and use it in GitHub Desktop.
"better" solution for OO birds problem
#include <iostream>
#include <cassert>
class FlyStyle
{
public:
virtual void Fly() const = 0;
};
class FlyHigh : public FlyStyle
{
virtual void Fly() const
{
std::cout << "Fly high!" << std::endl;
}
};
class NoFly : public FlyStyle
{
virtual void Fly() const
{
std::cout << "No fly!" << std::endl;
}
};
class SpeakStyle
{
public:
virtual void Speak() const = 0;
};
class SpeakLoud : public SpeakStyle
{
virtual void Speak() const
{
std::cout << "Speak LAUD!!!!" << std::endl;
}
};
class NoSpeak : public SpeakStyle
{
virtual void Speak() const
{
std::cout << "No speaking!" << std::endl;
}
};
class SuperBird
{
public:
SuperBird(FlyStyle* fly, SpeakStyle* speak)
: flystyle(fly),
speakstyle(speak)
{
assert(NULL != flystyle);
assert(NULL != speakstyle);
}
~SuperBird() { delete flystyle; delete speakstyle;}
virtual void Fly() const
{
flystyle->Fly();
}
virtual void Speak() const
{
speakstyle->Speak();
}
protected:
FlyStyle* flystyle;
SpeakStyle* speakstyle;
};
class SuperBirdFactory
{
public:
static SuperBird* createEagle()
{
return new SuperBird(new FlyHigh(), new SpeakLoud());
}
static SuperBird* createPenguin()
{
return new SuperBird(new NoFly(), new NoSpeak());
}
};
int main()
{
SuperBird* bird = NULL;
bird = SuperBirdFactory::createEagle();
bird->Fly();
bird->Speak();
delete bird; bird = NULL;
bird = SuperBirdFactory::createPenguin();
bird->Fly();
bird->Speak();
delete bird; bird = NULL;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment