Observer mode [Observer]

Source: Internet
Author: User

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 ();
}
}

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.