Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create decorator chain

I have a decorator chain that looks like this when initially created:

IType calculator = new TypeADecorator(
                            new TypeBDecorator(
                                    new TypeCDecorator(
                                        new MyCalculator())));

Each of these decorators does a database look up to get a piece of data which is used in a calculation

However, not all of these decorators will be used each time. Therefore, there will potentially be redundant database calls that return nothing

So I am thinking it would better to dynamically create the decorator chain based on which ones do get used

e.g.

If I had a bool representing each one that gets used:

bool useTypeA;
bool useTypeB;
bool useTypeC;

Would I be able to somehow dynamically construct the necessary chain?

Bear in mind that it's highly likely that other decorators will be added throughout the life of the app so I would like to come up with something that is quite flexable. Also, although there are only three decorators here, in reality there are about 8 used at the moment

like image 980
ChrisCa Avatar asked Aug 15 '26 17:08

ChrisCa


1 Answers

Yes, now you need to read about the Builder Pattern.

like image 118
DanDan Avatar answered Aug 17 '26 06:08

DanDan