I completely understand the Observer design pattern, what it is for and how to implement it. I also understand what the term ‘loosely-coupled’ means.
But I’m not sure how Observer makes designs more loosely-coupled.
For example, let’s say I want objects B and C to get updates from object A about it’s state. The Observer pattern is a great way to do that. But one could also implement this with a more ‘brute-force’ way, not using the pattern.
Please explain to me how the Observer pattern allows for more loosely-coupled designs. I’m not sure I completely understand. Thanks
(Again, I understand what ‘loosely-coupled’ means, but not exactly how Observer allows for designs to be more loosely-coupled).
0
By using the observer pattern, A needs not know about B or C. If you explicitly had A call B and C then it would necessarily know about B and C.
Depending on how you do it, B and C don’t even know about A, some D ties them all together.
That “lack of knowledge” is at the core of decoupling components.
4
The simplest way to implement the observer pattern is to define two interfaces, say ISource and ISink in a type library.
Any objects that can send signals implement ISource and any objects that can receive signals implement ISink. These implementations depend on the type library, but do not need to contain any references to each other.
In your application you can then connect up your objects ISource and ISink interfaces without either class needing to have knowledge of the other objects implementation.
If you read the book GoF Book, there you will find the answer to your question in applicability section of the Observer pattern (page 294).
Applicability Use the Observer pattern in any of the following situations:
- When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and
reuse them independently.- When a change to one object requires changing others, and you don’t know how many objects need to be changed.
- When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don’t
what these objects tightly coupled.
There are a few keywords here: ‘encapsulating’, ‘vary and reuse independently’, ‘a change in one object affecting others’, and ‘making assumption about objects’.
This can guide you in your investigation to understand the patter much better. Also, it may be a good idea to get a copy of the GoF book and give it a read.