views:

60

answers:

2

Is the Decorator Pattern mainly to get an object with dynamically chosen extra functionalities?

Can we do something like

window = Window.new(widht, height, x, y, [UseScrollBar.new, DrawBorder.new])

so that when we call draw(), we also loop through the additional functionalities?

For example, if our purpose is to write_line to a file, with nesting, we have to write multiple times (multiple lines to the file), but with the loop, we can be more flexible about what we do: have the line of text, but loop through the list of extra functionalities, so if it is empty, we write the plain line, but if there is AddLineNumber, or AddTimeStamp, then the line is modified, and then a single line is written to the file.

I hope I understand the pattern enough to give an accurate question. Do some people implement the Decorator Pattern using a list of extra functionalities instead of nesting?

A: 

my feeling is that it can. whether it is a list of additional function or nested, it should still be able to provide additional functionalities.

動靜能量
+1  A: 

It depends whether the list of the added functionlities is fixed or should be flexible. You can also have some kind of builder to create the chain for you:

window = WindowBuilder.new
                      .setWidth(w)
                      .setHeight(h)
                      .setX(x)
                      .setY(y)
                      .addScrollBar(scrollBar)
                      .addBorder(border)
                      .getWindow(h);

and in you will be a BorderDecorator points to the Scroll bar decorator, points to the actual window.

David Rabinowitz