Lecture thumbnail 0:03 / 2:34 In this section of the course, we’re going to look at the decorator design pattern.

Now, just like many other design patterns, the decorator is all about trying to add behavior to existing

classes without really altering the classes themselves.

So as you probably remember, we have agreed at the beginning of the course that jumping back into the

code that’s already written, that’s already tested and altering that code is not a great idea.

I mean, even if you have continuous testing and you have 100% test coverage, it’s still not a great

idea to go into something that already works and people might already be using and attempting to change

it because you never know where you can mess up and change it in a way which breaks something.

So the decorator is all about adding behavior on the side without actually altering the original component.

So the motivation for using the decorator pattern is fairly obvious.

So we want to augment an object with additional functionality, but we don’t want to rewrite or alter

existing code.

So we want to stick to the open or closed principle.

And in addition we want to keep the new functionality separate.

So the new functionality relates to yet another feature which can be kept as separate, and that’s the

single responsibility principle.

So we need to be able to interact with existing structures.

So our decorated object has to have certain traits of the original object and we’ll see whether or not

we can actually get this and how we can get this.

And essentially, in this case, you have two fundamental options.

So if you have a class which is not sealed, then what you can try doing is inheriting from the required

object.

And that way you get all of its traits and you can add some additional traits on the side.

So inheritance is a good approach.

However, the problem is that some objects are sealed.

So for example, if you take something like a stringbuilder, you cannot just go ahead and inherit from

a stringbuilder because it’s sealed and so you end up having to aggregate the stringbuilder and then

replicating some of its APIs.

So what you do instead is you build something called a decorator.

So a decorator simply references the decorated object, and then it actually provides additional behavior

on top of the behavior of those objects.

And remember that because you don’t have inheritance, you have to replicate the API and proxy the calls,

which resharper actually helps you do.

So the decorator facilitates the addition of behaviors to individual objects without actually inheriting

from them.

That’s the key part about the decorator.

Stop Play Play Play Play Play Play Play Play Start Play information alert