The Decorator

Decorator pattern is the most useful and mostly used in Software Engineering. So what is it about?

Have you face a problem when you already have a working code but you need to extend the code to do something more. For instance, I created an Angular’s service that has responsibilities to handle user creations and authentication.

Let’s zoom into the createUser() function. Inside the function it will call the Firebase’s AngularFire library who will handle the creation of the user and return a Promise. The library will only created the user id, email, and password but it won’t save the other user’s information for instance the user’s full name and other details. We can modify the function to also handles the creation of the other details but we also have another better option that is to decorate the class with another class that has responsibilities to create the additional details. That way we can achieve one of the requirements of SOLID Principles that is separation of concerns.

So this is the decorator class that will have the responsibility to create the additional details:

Inside the decorator createUser() function we call the original createUser() method of the original class and after that we add the code to save the user details. Ideally this should run inside a database transaction but I am not sure if Firebase’s transaction can support this kind of operation.

Inside the client’s code we need to pass the original class instance into the decorator instance:

We don’t need to strictly followed the class hierarchy of the Decorator pattern because we are using a loosely type language, JavaScript, and this is one of the strength the language if we know how to use it correctly.

This is the original class hierarchy of the Decorator pattern: