Design patterns implementation examples

Decorator

Definition:

Adds dynamically new behaviors to an existing object without changing its inferface. An alternative way to inheritance but more flexible because you can add new behaviors at runtime.


Example:

For instance we have computer to which we connect an USB device, computer is still a computer (the same interface) but it works differently and allows us to perform other functions. Once we remove a device form USB port the computer is no longer so cool. A device might be connected dynamically, meaning while the computer is on - we don't have to turn the computer off in order for a device to work. For instance a pen drive adds new disc and therefore extends computer's memory.


C++ code:

/src/decorator.cpp
Download source code

Decorator UML class diagram:
Decorator UML class diagram

Decorator UML sequence diagram:
Decorator UML sequence diagram