Sketched quickly by hand, please do not strongly scold, such things must be carefully thought out. And the final result may vary from task. The idea is to create a decorator that aggregates other decorators with the right priority.
#include <iostream> #include <map> using namespace std; //Π΄Π΅ΠΊΠΎΡΠΈΡΡΠ΅ΠΌΡΠΉ ΠΊΠ»Π°ΡΡ class Entity { public: virtual void d() { cout <<"Entity"<<endl; } }; //ΠΊΠ»Π°ΡΡΠΈΡΠ΅ΡΠΊΠΈΠΉ Π΄Π΅ΠΊΠΎΡΠ°ΡΠΎΡ class Decorator : public Entity { public: Decorator() :m_entity(NULL) { } explicit Decorator(Entity* ent) :m_entity(ent) { } virtual void d() { if(m_entity) m_entity->d(); } private: Entity* m_entity; }; //ΠΊΠ»Π°ΡΡΠΈΡΠ΅ΡΠΊΠΈΠΉ ΠΊΠΎΠ½ΠΊΡΠ΅ΡΠ½ΡΠΉ Π΄Π΅ΠΊΠΎΡΠ°ΡΠΎΡ 1 class Decor1 : public Decorator { public: Decor1() { } explicit Decor1(Entity* ent) :Decorator(ent) { } virtual void d() { Decorator::d(); cout <<"Decor1"<<endl; } }; //ΠΊΠ»Π°ΡΡΠΈΡΠ΅ΡΠΊΠΈΠΉ ΠΊΠΎΠ½ΠΊΡΠ΅ΡΠ½ΡΠΉ Π΄Π΅ΠΊΠΎΡΠ°ΡΠΎΡ 2 class Decor2 : public Decorator { public: Decor2() { } explicit Decor2(Entity* ent) :Decorator(ent) { } virtual void d() { Decorator::d(); cout <<"Decor2"<<endl; } }; //ΠΊΠ»Π°ΡΡΠΈΡΠ΅ΡΠΊΠΈΠΉ ΠΊΠΎΠ½ΠΊΡΠ΅ΡΠ½ΡΠΉ Π΄Π΅ΠΊΠΎΡΠ°ΡΠΎΡ 3 class Decor3 : public Decorator { public: Decor3() { } explicit Decor3(Entity* ent) :Decorator(ent) { } virtual void d() { Decorator::d(); cout <<"Decor3"<<endl; } }; //Π²ΠΎΡ ΠΎΠ½ Π΄Π΅ΠΊΠΎΡΠ°ΡΠΎΡ - ΠΊΠΎΠΌΠ±ΠΈΠ½Π°ΡΠΎΡ class CombineDecorator : public Decorator { public: explicit CombineDecorator(Entity* ent) { m_entities.insert(std::make_pair(100500, ent)); } void add(int order, Entity* ent) { m_entities.insert(make_pair(order, ent)); } void remove(int order, Entity* ent) { m_entities.erase(order); } void d() { for (EntityMap::iterator i = m_entities.begin(); i!= m_entities.end(); ++i) { i->second->d(); } } private: typedef std::map<int, Entity*> EntityMap; EntityMap m_entities; }; int main() { //ΠΎΠ±ΡΡΠ½ΠΎΠ΅ ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅ Entity* ent = new Entity(); ent = new Decor1(ent); ent = new Decor2(ent); ent->d(); cout <<"========"<<endl; //ΠΊΠΎΠ±ΠΈΠ½Π°ΡΠΎΡ ΠΎΡΠ΄Π΅Π»ΡΠ½ΠΎ Entity* ent2 = new Entity(); CombineDecorator* cd = new CombineDecorator(ent2); cd->add(3, new Decor1()); cd->add(4, new Decor2()); cd->add(2, new Decor3()); ent2 = cd; ent2->d(); cout <<"========"<<endl; //ΡΠΎΠ²ΠΌΠ΅ΡΡΠ½ΠΎΠ΅ ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅ cd->add(6, ent); ent2->d(); }