When you say "know", you're right that the publisher must know about the observer in order to publish information to it.
However, it doesn't need to "know" about it in the sense that it is hardcoded that:
- The observer is always going to be this particular class
- There is always going to be these particular observers available
In its basic form, events are publisher/observer in play, so you can easily do this just with events:
public class Observer
{
}
public class Publisher
{
public event EventHandler SomethingHappened;
}
You would then make the observer handle that event:
public class Observer
{
public Observer(Publisher pub)
{
pub.SomethingHappened += Publisher_SomethingHappened;
}
private void Publisher_SomethingHappened(object sender, EventArgs e)
{
}
}
public class Publisher
{
public event EventHandler SomethingHappened;
}
Whenever this event is raised from the publisher, the observer is informed about it. Realize that the act of hooking into an event is to "tell" that class about the observer, but the publisher doesn't have any hardcoded information about the publisher, except that there is someone out there listening.
A different way would be using interfaces:
public class Observer : IObserver
{
public Observer(Publisher pub)
{
pub.Observers.Add(this);
}
void IObserver.SomethingHappened()
{
}
}
public class Publisher
{
public List<IObserver> Observers { get; private set; }
}
public interface IObserver
{
void SomethingHappened();
}
Again, the publisher will "know" about the observer in the sense that it has a reference to it, but again it has no hardcoded information about which class or how many instances there will be.
Just a word of warning: The code above is very flawed, at a minimum you should ensure that the observer "unhooks" from the publisher when you're done, otherwise you're going to have leaks in the system. If you don't understand what I mean by that, leave a comment and I'll edit in an example.