Add to Favorites

Programming - Observer Pattern

Do you find yourself in a situation where you need to create a set of loosely coupled components in your application that can be swapped out. Is there an event or operation that requires that some of these components perform an action but you want to keep each component blind from each other to keep from creating a web of interdependency?

Then you may just be in need of an event/observer system in your application. Many applications have plugins and in order to manage execution of the plugin code in the appropriate places, events are used to trigger plugins without having to hard code in calls to the individual plugins.

For example, lets say you build a system that handles user authentication and management of said users. You want to extend that functionality by adding a user profile that is related in the database to a user. You want the profile to be deleted with the user when the user is deleted from your user management screen. However you do not want to make the dependency in your user management screen to delete the profile.

You can create a central event register, when your system initializes and loads your user profile plugin the plugin can register to be notified when a user is deleted. Now your user management screen just needs to fire off the event on the central event register and that register will take responsibility for calling the user profile plugin to have the profile deleted.

This can become quite useful when programming large applications that have many interconnected parts. No longer will you have to worry about what is going on in the other parts as long as you fire the right events when you perform actions.

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up