7.5.1.2 THE DECORATOR DESIGN PATTERN)
7.5.1.2 THE DECORATOR DESIGN PATTERN)
Similar to the composite mode, decoratorpattern aims to add new behaviors to existing classes at runtime. As shown in figure 7.7, the structure is very similar to the composite mode.
The two models look similar, but have different purposes. The purpose of the composite mode is to treat the composite value as the basic value, while the decoration mode is to add new functions for existing objects. As shown in figure 7.7, The DecoratedComponent class encapsulates an additional decoration component that can carry additional States (such as the decoration field ). Decoration components can also be added with additional statuses in the Operation method.
Figure 7.7 DecoratedComponent class wraps a component and adds a new state to it. In the decoration component, the Operation method calls the encapsulated function and adds a new behavior, the status of the decoration component.
In our document representation, we can also see the correspondence between this mode and the Document section. In our application, TitledPart is added to the other part. Decoration is the title, and the added status is the text and title Font. It indicates the F # type with the same structure as 7.7, which is as simple as the combination mode:
Type AbstractComponent =
"DecoratedComponent ofAbstractComponent *(...)
| ConcreteComponent (...)
| (...)
Here, the data carried by the decoration option is a list of decorated components (not a list of components in composite mode) and an additional state, which can be changed between different decorations. In the previous list, we used (...) in the real F # code, you can specify the actual status type, for example, TextContent in the header section. As in the composite mode, the code that implements operations on the decoration component is located in the processing function and implements the data structure for us. In the processing function, the code of the DecoratedComponent branch can call itself recursively, process the encapsulated component, and execute the behavior added by the decoration, for example, draw the title of the document section.
In this section, both modes implemented by F # depend on the use of recursive differential Union types. In the next section, we will use different methods and use object-oriented methods, add new operations for existing data types.