While studying decorator pattern I got stuck in a basic doubt as follows
Background: http://www.newthinktank.com/2012/09/decorator-design-pattern-tutorial/
Question: How does code executer reads the following code? I tried to answer it please do confirm whether it is correct or not.
So, TomatoSauce Object's super contains Mozzarella object. And that Mozzarella Object's super object contain PlainPizza object.
Pizza basicPizza = new TomatoSauce(new Mozzarella(new PlainPizza()));
Your are almost there with your understanding.
Pizza basicPizza = new TomatoSauce(new Mozzarella(new PlainPizza()));
PlainPizza
object will be created Mozzarella
constructor will be called by passing newly created plainpizza. Mozzarella
constructor will call the super(newPizza);
, this will set the newPizza
to ToppingDecorator
's instance variable. Mozzarella
object creation is completed. As the Mozzerella
is-a
Pizza
the TomotoSauce
constructor can take it and call the ToppingDecorator
's constructor and set the mozerella
to ToppingDecorator
.
Now, coming to decorator pattern
, it changes the behavior of a single instance of the Pizza
.
When you call a method basicPizza.getDescription();
your output will be Thin dough, mozzarella, tomato sauce
. This means you wrapped Thin dough
behavior with both mozzarella
and tomato sauce
.
If you just want to decorate your PlainPizza
with Mozzarella
, you do the following without changing any implementation.
Pizza onlyMozzarella = new Mozzarella(new PlainPizza());
Hope it will not make you further confused.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.