3

I often find myself creating class cycles by using the observer pattern. Consider the following scenario:

  • I have a central accessible global data source (Subject)
  • The data source is reflected by many GUI components (Observers) in various ways (e.g. different states for buttons, size indicators, numbers, etc.)
  • Some of those GUI components (like buttons) can update the global data source (e.g. a button can remove something from the data source or it shows as disabled if the data source is empty)

So now I have a cycle between some GUI components and the data source.

Do I abuse the observer pattern here for something it is not meant for? Is there another way to solve this?

3
  • 1
    Looks like its broadly correct, the repository is communicating its state to all who are interested, and some of those who are interested may decide to instruct the repository to undertake an action. So far so good. Is your problem an infinite loop of messages?
    – Kain0_0
    Mar 20, 2020 at 0:16
  • I don't really have a problem. The system is working as expected. I am just wondering if this is the correct design or if there is a better solution. Thanks for the answer! Mar 20, 2020 at 7:27
  • Provided the button (for example) updates the data source in reaction to user input, then that is fine. Where things can get messy is when there are recursive cycles of reactivity not controlled by the user, or when there are dependencies between observers.
    – Steve
    Mar 20, 2020 at 7:31

1 Answer 1

9

There is no cycle.

The repository does not know the gui if you do it correctly. The respository knows of an observer interface and sends its messages to the interface implementations that are set from the outside.

The gui knows the repository, as it

  • registers itself as an observer (i.e. implementation of that interface)
  • issues commands to the repository as a reaction to user input

Thus, you have two dependencies from the gui to the repository, but no dependency from the repository to the gui. => no cycle here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.