Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@dlivingstone dlivingstone commented Jun 27, 2012

I have not dealt fully with destructors in these examples

@dragonhades

This comment has been minimized.

Copy link

@dragonhades dragonhades commented Nov 16, 2016

Very helpful, thx.

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