lundi 14 décembre 2020

Decorator pattern incorrect order calling

I have created some class which using Decorator pattern.
Main idea: I get some text, and I need add line number for each string, add HTML tags, add color tag for some word.
Everything works fine as long as I control the order (sequence) of calling the Decorator function myself, e.g:

std::shared_ptr<WriterComponent> result = std::make_shared<ColorDecorator>(std::make_shared<LineDecorator>(std::make_shared<HTMLTagDecorator>(std::make_shared<Writer>(ss.str())))); //writerComponent it's abstract with pure virtual method write_changes()

The problem: If I call first added HTML Tag decorator and then add line number Decorator - then the HTMLed string will also counted, and that's not what I want. The same for other, e.g: First add line, then add html tag:

<html>
1| some text
</html>

First add tag then line:

1| <html>
2| some text
3| </html>

I found similar, but not exact question about that problem.
Common cases: Actually, there is a problem, if in real life you first put on jacket and then a shirt.
I think that there should be some delegate classes where I should deny called from some decorator another decorator, but I don't exactly know how it should be.
Yes, maybe there is a bad decision to use Decorator pattern here, but what If it was already done? How should we avoid this problem, if somebody else want to call it with incorrect order?

Aucun commentaire:

Enregistrer un commentaire