Long-known Wraper or Decorator design pattern

Here is an example on java from wikipedia

 abstract class WindowDecorator extend Window { protected Window windowToBeDecorated; // the Window being decorated public WindowDecorator (Window windowToBeDecorated) { this.windowToBeDecorated = windowToBeDecorated; } public void draw() { windowToBeDecorated.draw(); //Delegation } public String getDescription() { return windowToBeDecorated.getDescription(); //Delegation } } 

So, I don’t quite understand why to transfer a class object from which to inherit to a wrapper?

With inheritance, we already get all the same and can directly call ...

  • I see interface implementation here and no inheritance - pavlofff
  • @pavlofff sorry, fixed. But the essence of the issue has not changed because of this - Aleksey Timoshchenko
  • because any heir can be passed inside - etki
  • Now in the example to which you refer there is no inheritance, but there is an interface implementation, you may need to fix Wikipedia or read more carefully what is written there :) - pavlofff

2 answers 2

The essence of such an implementation of the decorator is that it adds functionality to any already existing object.

If the object is under your control, then you can really inherit from it and add / change the necessary functionality yourself. But if an object is created / configured / configured not by you or not under your control, then you will not be able to make a duplicate on your own, and you will have to proxy calls, as this is done in the pattern you mentioned.

    The main difference between the декоратор pattern and inheritance is that the functionality expands dynamically and at the level of objects, not classes, as in inheritance. This can be useful, for example, when there are a large number of combinations of functionality, which in normal inheritance will require the creation of a huge number of subtypes or, for example, when functionality should be added for some objects and not for the entire type (class) or if it is not possible to change the implementation of which something class.

    So, I don’t quite understand why to transfer a class object from which to inherit to a wrapper?

    The object that decorates your “original” object should not change its type, otherwise we will not be able to talk about extending the properties of the same object.

    • one
      Yeah, arbitrary combinability is important too. - VladD