-
-
Save l4es/42588152abb575c1d6b64b71538e42fc to your computer and use it in GitHub Desktop.
Simple C++ Decorator Pattern example
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
// Simple decorator pattern example | |
// (c) Daniel Livingstone 2012 | |
// CC-BY-SA | |
#include <string> | |
#include <iostream> | |
using namespace std; | |
class AbstractNPC { | |
public: | |
virtual void render() = 0; | |
}; | |
class NPC: public AbstractNPC { | |
private: | |
string name; | |
public: | |
NPC(string basename) { name.assign(basename); } | |
NPC(char * basename) { name.assign(basename); } | |
void render() { cout << name; } | |
}; | |
class NPCDecorator: public AbstractNPC { | |
private: | |
AbstractNPC * npc; | |
public: | |
NPCDecorator(AbstractNPC *n) { npc = n; } | |
void render() { npc->render(); } // delegate render to npc data member | |
}; | |
class Elite: public NPCDecorator { | |
public: | |
Elite(AbstractNPC *n): NPCDecorator(n) { } | |
void render() { | |
cout << "Elite "; // render special features | |
NPCDecorator::render(); // delegate to base class | |
} | |
}; | |
class Captain: public NPCDecorator { | |
public: | |
Captain(AbstractNPC *n): NPCDecorator(n) { } | |
void render() { | |
cout << "Captain "; // render special features | |
NPCDecorator::render(); // delegate to base class | |
} | |
}; | |
class Shaman: public NPCDecorator { | |
public: | |
Shaman(AbstractNPC *n): NPCDecorator(n) { } | |
void render() { | |
NPCDecorator::render(); // delegate to base class | |
cout << " Shaman "; // render special features *after* base | |
} | |
}; | |
int main(int argc, char **argv) | |
{ | |
AbstractNPC *goblin1= new Elite(new Shaman(new NPC("Goblin"))); | |
AbstractNPC *orc1= new Elite(new Captain(new NPC("Orc"))); | |
goblin1->render(); cout << endl; | |
orc1->render(); cout << endl; | |
delete goblin1; | |
delete orc1; | |
cin.get(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment