So-called observer Mode
Define one-to-multiple dependencies between objects. In this way, when an object changes its state, all objects dependent on it receive notifications and update automatically.
Actually, it is easy to understand
That is, the observer observes the person observed ..
For example, when a reader subscribes to a publishing house, the agreement between the two parties is that once the publishing house publishes a book, the reader can receive the book.
He can also Unsubscribe.
In this case, is it easy to think of delegation and events?
Unfortunately, the second half of head first's explanation of this mode is Java (in fact, all of them are Java, but the second half cannot be written in the. net environment)
// This example is not accurate, because I wrote it myself --!, But the problem should be explained.
// This is a story about cats and mice.
Public delegate void Mydelegate ();
// Define the observer (event initiator)
Public abstract class subject
{
Public event Mydelegate Myevent;
Protected virtual void OnPublish ()
{
If (Myevent! = Null)
Myevent ();
}
Public abstract void publish ();
}
// Define the observer (event reception)
Public abstract class observer
{
// Register an event
Public observer (subject s)
{
S. Myevent + = dosomething;
}
Public abstract void dosomething ();
}
// A cat
Public class cat: subject
{
Public override void publish ()
{
Console. WriteLine ("miao ~~ Miao ~~ ");
Base. OnPublish ();
}
}
// A mouse
Public class mouse: observer
{
// When a mouse is instantiated, the information has been subscribed to the cat, so as to escape in the future
Public mouse (subject s)
: Base (s)
{}
Public override void dosomething ()
{
Console. WriteLine ("mouse escape away ");
}
}
Class Program
{
Static void Main (string [] args)
{
Cat c = new cat ();
Mouse m = new mouse (c );
// The mouse is running.
C. publish ();
Console. Read ();
}
}