S
S
Svyatoslav Khusamov2017-03-17 00:54:17
OOP
Svyatoslav Khusamov, 2017-03-17 00:54:17

How to reduce the number of classes without using decorators?

Below is an example. It's made on decorators. And why is it better than this implementation:
Make an ElementStyle class, from which to make inheritance in the form of many different styles: ElementStrikedStyle, ElementHighlightedStyle, ElementInvertedStyle.
For the Element class, make the styles property as an array of elements of type ElementStyle. You can put any number in any combination of different styles into it.
As a result, we achieved the same result (the same 4 classes, except for the parent), but we don’t need to spend time learning decorators.
Here is an example on decorators (taken from here andrey.moveax.ru/post/patterns-oop-structural-deco...

Example of Reducing the Number of Classes
Suppose you want to develop an Element class that implements a flowchart element. There are four styles of its display that must be combined: default, inverted (inverted), strikethrough (striked), selected (highlighted). In addition, it is necessary to easily add new styles and their combinations in the future.
When using inheritance, we get 8 classes: from Element, ElementInverted, ElementStriked, ElementHighlighted, ElementInvertedStriked and up to ElementInvertedStrikedHighlighted. Adding another style, such as a frame (ElementBorder), will increase the number of classes to 16. It is hardly possible to call this a convenient, simple and reliable solution.
Using the Decorator pattern will limit the number of generated classes to 4: the main Element and 3 Decorators (ElementInvert, ElementStrike, ElementHighlight). In the future, it is possible to invest them one into the other to achieve the desired result. In addition, this approach is more flexible in work. For example, you can first invert, and then highlight, or vice versa. And it's easier to maintain such code.

Here is the question. Why do we need decorators if the same task can be solved in a simpler and more understandable way in OOP?
And plus the solution is more flexible. Decorators cannot be inherited. And here we can safely make a child, for example, of the ElementHighlightedStyle class (for example, ElementColorHighlightedStyle).

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question