Skip to main content

Decorator

  • Chapter
  • First Online:
Design Patterns in .NET
  • 1627 Accesses

Abstract

Suppose you’re working with a class your colleague wrote, and you want to extend that class’s functionality. How would you do it without modifying the original code? One approach is inheritance: You make a derived class, add the functionality you need, maybe even override something, and you’re good to go.

This is a preview of subscription content, log in via an institution to check access.

Access this chapter

Chapter
USD 29.95
Price excludes VAT (USA)
  • Available as PDF
  • Read on any device
  • Instant download
  • Own it forever
eBook
USD 34.99
Price excludes VAT (USA)
  • Available as EPUB and PDF
  • Read on any device
  • Instant download
  • Own it forever

Tax calculation will be finalised at checkout

Purchases are for personal use only

Institutional subscriptions

Notes

  1. 1.

    Strictly speaking, it is possible to store state in extension methods, albeit in a very roundabout way. Essentially, what you would do is have your extension class keep a static member of type Dictionary<WeakReference, Dictionary<string,object>> and then modify the entries in this dictionary to map an object to its set of properties. Plenty of fiddling is required here, both in terms of working with weak references (we don’t want this store to extend the lifetime of the original object, right?) as well as the boxing and unboxing that comes with storing a bunch of objects.

  2. 2.

    CRTP is a popular C++ pattern that looks like this: class Foo<T> : T. In other words, you inherit from a generic parameter, something that is impossible in C#.

  3. 3.

    Mixin inheritance is a C++ technique for adding functionality to classes by using inheritance. In the context of the Decorator, it would allow us to compose a class of type T<U<V>> that would inherit from both U and V, giving us access to all the underlying members. Also, constructors would work correctly thanks to constructor forwarding and C++’s variadic templates.

Author information

Authors and Affiliations

Authors

Rights and permissions

Reprints and permissions

Copyright information

© 2019 Dmitri Nesteruk

About this chapter

Check for updates. Verify currency and authenticity via CrossMark

Cite this chapter

Nesteruk, D. (2019). Decorator. In: Design Patterns in .NET. Apress, Berkeley, CA. https://doi.org/10.1007/978-1-4842-4366-4_10

Download citation

Publish with us

Policies and ethics