Decoration through constructor injection versus simple inheritance

Can someone let me through the differences between (as in the benefits) of creating decorator classes using the injection constructor of another class as opposed to class inheritance? In the examples that I can think of, I could achieve the same ultimate goal in one of two ways, but I suspect that I do not have something fundamental.

+6
source share
3 answers

A sample decorator concerns the layout of an object. To inherit the type of this object, it must be inherited. Not all types are intended to be inherited, i.e. Designed for base classes, even if they can be inherited from a purely technical point of view (which I consider a design flaw).

The design of the decorator is based on the ability to change the behavior of objects without changing the objects themselves. By inheriting, you essentially modify the object itself, and what you get is a regular behavioral change through polymorphism, which means that you have not performed the same thing.

Thus, both decoration and inheritance use them. Use jewelry when one of them is right.

  • you cannot inherit (e.g. if the class is sealed in C #)
  • you should not inherit (the class is clearly not intended for the base class)
  • you want to change the behavior of one specific object many times (by wrapping it with decorators of different behaviors)

Note that inheritance is the most powerful tool in the OO toolbar. With great power comes great responsibility and which is not always easy to handle. I would say: always make up or combine. When it is simply impossible to do, inherit. If you cannot inherit, try harder to compose or fill out. "

+4
source

I would do the following:

When should you inherit?

When objects from the same semantic hierarchy represent an is-a relationship.

What does it mean?

What a Cat is-a Feline , really a Feline is-a Vertebrate , etc.

When should you decorate?

When objects do not represent an is-a relationship. But, yes, both Coffee and Milk can be in the same hierarchy. But if you were to sell Cappuccino , you would not say that coffee is-a Milk, instead you'd decorate it with Milk .

Conclusion:

Is-a is different from has-a . One is a subtype , the other is part of the composition.

But here's what: https://stackoverflow.com/questions/1621344/head-first-design-patterns-decorator-pattern

An example of a real world would be to create a security container as a Decorator for your controllers or services for checking ACLs.

0
source

Another really good reason to decorate is that it gives you the opportunity to decorate an interface instead of a class. Then you become rather loosely coupled and can add orthogonal design to several interface implementations without writing more code.

0
source

Source: https://habr.com/ru/post/923804/


All Articles