Skip to content

Instantly share code, notes, and snippets.

@dlivingstone
Created June 27, 2012 19:43
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save dlivingstone/3006324 to your computer and use it in GitHub Desktop.
Save dlivingstone/3006324 to your computer and use it in GitHub Desktop.
Simple C++ Decorator Pattern example
// 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;
}
@dlivingstone
Copy link
Author

I have not dealt fully with destructors in these examples

@dragonhades
Copy link

Very helpful, thx.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment