ArticleslgStudy

computer science

Decorator pattern

Decorator pattern is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Decorator pattern rather than just read about it. In short: In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object dynamically, without affecting the behavior of other instances of the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it enables functionality to be distributed across classes with distinct concerns.

Decorator pattern — main illustration
Decorator pattern — illustration

Key takeaways

  • Decorator pattern belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Decorator pattern to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Decorator pattern from memory before moving on to harder problems.

Reference excerpt

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object dynamically, without affecting the behavior of other instances of the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it enables functionality to be distributed across classes with distinct concerns. It also supports the Open–Closed Principle, since a class's functionality can be extended without modifying its source code. Using decorators can be more flexible and efficient than subclassing, as an object's behavior can be augmented or combined at runtime without creating an entirely new class hierarchy.

Overview The decorator design pattern is one of the twenty-three Gang-of-Four design patterns; these describe how to solve recurring design problems and design flexible and reusable object-oriented software—that is, objects which are easier to implement, change, test, and reuse. The decorator pattern provides a flexible alternative to subclassing for extending functionality. When using subclassing, different subclasses extend a class in different ways. However, an extension is bound to the class at compile-time and can't be changed at run-time. The decorator pattern allows responsibilities to be added (and removed from) an object dynamically at run-time. It is achieved by defining Decorator objects that

implement the interface of the extended (decorated) object (Component) transparently by forwarding all requests to it. perform additional functionality before or after forwarding a request. This allows working with different Decorator objects to extend the functionality of an object dynamically at run-time.

Intent

The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new Decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps:

Subclass the original Component class into a Decorator class (see UML diagram); In the Decorator class, add a Component pointer as a field; In the Decorator class, pass a Component to the Decorator constructor to initialize the Component pointer; In the Decorator class, forward all Component methods to the Component pointer; and In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified. This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s). Note that decorators and the original class object share a common set of features. In the previous diagram, the operation() method was available in both the decorated and undecorated versions. The decoration features (e.g., methods, properties, or other members) are usually defined by an interface, mixin (a.k.a. trait) or class inheritance which is shared by the decorators and the decorated object. In the previous example, the class Component is inherited by both the ConcreteComponent and the subclasses that descend from Decorator. The decorator pattern is an alternative to subclassing. Subclassing introduces additional behavior by deriving new classes at compile time, and such modifications affect all instances of the original class. In contrast, the Decorator pattern allows new behaviors to be dynamically added to selected objects at run-time without impacting other instances of the same class. This design enables more fine-grained and flexible behavior extension, thereby improving code reusability and maintainability. This difference becomes most important when there are several independent ways of extending functionality. In some object-oriented programming languages, classes cannot be created at runtime, and it is typically not possible to predict, at design time, what combinations of extensions will be needed. This would mean that a new class would have to be made for every possible combination. By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis. The I/O Streams implementations of both Java and the .NET Framework incorporate the decorator pattern.

Motivation

As an example, consider a window in a windowing system. To allow scrolling of the window's contents, one may wish to add horizontal or vertical scrollbars to it, as appropriate. Assume windows are represented by instances of the Window interface, and assume this class has no functionality for adding scrollbars. One could create a subclass ScrollingWindow that provides them, or create a ScrollingWindowDecorator that adds this functionality to existing Window objects. At this point, either solution would be fine. Now, assume one also desires the ability to add borders to windows. Again, the original Window class has no support. The ScrollingWindow subclass now poses a problem, because it has effectively created a new kind of window. If one wishes to add border support to many but not all windows, one must create subclasses WindowWithBorder and ScrollingWindowWithBorder, etc. This problem gets worse with every new feature or window subtype to be added. For the decorator solution, a new BorderedWindowDecorator is created. Any combination of ScrollingWindowDecorator or BorderedWindowDecorator can decorate existing windows. If the functionality needs to be added to all Windows, the base class can be modified. On the other hand, sometimes (e.g., using external frameworks) it is not possible, legal, or convenient to modify the base class. In the previous example, the SimpleWindow and WindowDecorator classes implement the Window interface, which defines the draw() method and the getDescription() method that are required in this scenario, in order to decorate a window control.

Common usecases

… excerpt ends here. Continue reading the full article.

Illustrations

Decorator pattern: UML diagram for the window example
UML diagram for the window example
Decorator pattern: A sample UML class and sequence diagram for the Decorator design pattern[7]
A sample UML class and sequence diagram for the Decorator design pattern[7]

Worked examples

Example 1 — a first encounter with Decorator pattern

Start with the simplest possible case. Write down what Decorator pattern claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Decorator pattern before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Decorator pattern ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Decorator pattern

In research
Decorator pattern appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Decorator pattern in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Decorator pattern is common in secondary-school and first-year university syllabi. It links to neighbouring topics Software design patterns, so understanding it makes those chapters shorter.
In everyday life
Look for Decorator pattern outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Decorator pattern” →

How to study Decorator pattern in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Decorator pattern means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Decorator pattern out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Decorator pattern in simple terms?

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object dynamically, without affecting the behavior of other instances of the same class. The decorator pattern is often useful for adhering to the Single Responsibility Princi…

Why does Decorator pattern matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Decorator pattern?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Decorator pattern.

Tags

  • Software design patterns

Keep exploring