How can you cleanly add behavior to your object at execution time?

How can you cleanly add behavior to an object at execution time?

Let's assume that we are working on a renting book application. Anyone can choose an online book for renting by filing a straightforward application.

The system has a service that runs once per day and sends reminder e-mails to the renters before three days of the returning book period. The renters could choose more notification types like sending SMS or even a Whatsapp message.

Once the service runs, it gets the needed rental applications based on a certain query, then starts sending the e-mail.

What about SMS and Whatsapp message? It is simple, we can do some "if" conditions to know the selected options and that's it.

But.

What if determining the selected options is not simple, and there is a complex business behind it? What if the determining logic is needed in many places in the application?

The clean way is using the Decorator pattern.

The decorator pattern gives us the ability to add dynamic behavior on execution time instead of using inheritance which might lead to a huge number of classes to define all possible choices.

I highly recommend checking out the following link to know more about the Decorator pattern, how to implement it, and its pros and cons.

https://refactoring.guru/design-patterns/decorator

I hope this simple example helps you memorize the main purpose of Decorator and you use it next time in your application.

Let me know if you find it useful :)

Nicholas Ocket

I turn developers into software design experts. Join the About Coding Dojo!

3 年

Very nice Tarek! Well done!

要查看或添加评论,请登录

Tarek Haydar的更多文章

社区洞察

其他会员也浏览了