Created
February 27, 2011 15:37
-
-
Save nazgob/846263 to your computer and use it in GitHub Desktop.
"better" solution for OO birds problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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