Observer Design Pattern - multiple event types

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2011-01-14T15:51:09Z Indexed on 2011/01/14 15:53 UTC
Read the original article Hit count: 228

Filed under:
|

I'm currently implementing the Observer design pattern and using it to handle adding items to the session, create error logs and write messages out to the user giving feedback on their actions (e.g. You've just logged out!).

I began with a single method on the subject called addEvent() but as I added more Observers I found that the parameters required to detail all the information I needed for each listener began to grow.

I now have 3 methods called addMessage(), addStorage() and addLog(). These add data into an events array that has a key related to the event type (e.g. log, message, storage) but I'm starting to feel that now the subject needs to know too much about the listeners that are attached.

My alternative thought is to go back to addEvent() and pass an event type (e.g. USER_LOGOUT) along with the data associated and each Observer maintains it's own list of event handles it is looking for (possibly in a switch statement), but this feels cumbersome. Also, I'd need to check that sufficient data had also been passed along with the event type.

What is the correct way of doing this?

Please let me know if I can explain any parts of this further. I hope you can help and see the problem I'm battling with.

© Stack Overflow or respective owner

Related posts about php

Related posts about observer-pattern