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.
Access this chapter
Tax calculation will be finalised at checkout
Purchases are for personal use only
Notes
- 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.
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.
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
Rights and permissions
Copyright information
© 2019 Dmitri Nesteruk
About this chapter
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
DOI: https://doi.org/10.1007/978-1-4842-4366-4_10
Published:
Publisher Name: Apress, Berkeley, CA
Print ISBN: 978-1-4842-4365-7
Online ISBN: 978-1-4842-4366-4
eBook Packages: Professional and Applied ComputingApress Access BooksProfessional and Applied Computing (R0)