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?
-
1Looks 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– Kain0_003/20/2020 00:16:22Commented 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!Konstantin Hatvan– Konstantin Hatvan03/20/2020 07:27:06Commented 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– Steve03/20/2020 07:31:38Commented Mar 20, 2020 at 7:31
1 Answer 1
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
Explore related questions
See similar questions with these tags.