简体   繁体   中英

Regrading decorator pattern, object instantiation

While studying decorator pattern I got stuck in a basic doubt as follows

Background: http://www.newthinktank.com/2012/09/decorator-design-pattern-tutorial/

  • Pizza -> interface (PlainPizza & TopingDecorator(Abstract Class) implements it)
  • TomatoSauce and Mozzarella extends TopingDecorator
  • ToppingDecorator has an instance field Pizza

Question: How does code executer reads the following code? I tried to answer it please do confirm whether it is correct or not.

  1. TomatoSauce constructor creates its object passing Mozarella object to its super
  2. Its super (ie TopingDecorator) creates Mozzarella object (using its constructor) passing PlainPizza object as argument to its super.
  3. As soon as plain pizza object is instantiated, it is stored in the instance field Pizza of Mozzarella object.
  4. And then this Mozzarella object is stored in instance field of TomatoSauce. Now, the instantiation of TomatoSauce object is complete.

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()));
  • First, PlainPizza object will be created
  • Second, Mozzarella constructor will be called by passing newly created plainpizza.
  • Now, the Mozzarella constructor will call the super(newPizza); , this will set the newPizza to ToppingDecorator 's instance variable.
  • Now, the actual 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM