. Net Design Pattern-Observer Pattern

Source: Internet
Author: User
Summary

In today's design pattern series, I bring the observer pattern to everyone. First, I will introduce the observer pattern application scenario with a vivid story, and then describe the problems in this scenario, finally, we propose a solution for the observer mode and provide the Implementation of C # language.CodeAnd end with the observer mode in delegate-Event Mode in. net.

Story

Xiaoxue is a very beautiful girl. Pretty girls always have many pursuers, and their teams are constantly changing. At any time, some people enter this team and quit. When boys pursue girls, they always show 120% of their concerns. When Xiaoxue enjoys the game without permission, they always receive messages from the pursuers asking about the location change of Xiaoxue. Xiaoxue is also annoying, but Xiao Xue is such a kind girl. She always interrupts her normal life and replies to the boys. The boys are exhausted by constantly worrying about the changing position of light snow, which also affects normal work.

What did we find in such a simple story scenario? Let's take a look at the troubles of snow and boys:

Boys must constantly ask about the change in the position of the light snow to interrupt normal work.
Xiaoxue also needs to constantly accept the inquiry from boys. Sometimes, the position of Xiaoxue has not changed, so it is still necessary to continuously reply to the inquiry, which also affects normal work.
If there are different ways for boys to reply to questions, Xiao Xue also needs to know different ways of replying, and new boys are constantly increasing, I still don't know what new reply methods will be available in the future.

Seeing so many troubles, our creative Nokia company has proposed solutions for Xiao Xue and boys:
Nokia honors a mobile phone with the GPRS function, which stores a list of phone numbers that subscribe to location change text message notifications, when the mobile phone detects a location change, it will send text messages to all the mobile phones in the subscription list. Seeing the Nokia solution, boys and Xiao Xue should be relieved. They can communicate with each other only when their status changes.

Observer mode solution

In the above Nokia solution, the idea of the observer mode is revealed: The Observer mode defines one-to-many dependencies between objects. When the state of this object changes, multiple objects receive notifications and have the opportunity to provide feedback. You can dynamically add and delete observers at runtime.

With this definition, let's take a look at how to implement the above observer mode.

First, in the Observer mode, we must define an interface that all "observers" must implement, so that the observer can use a unified method when sending messages to the observer, this is also in line with interface-Oriented Programming in the face object principle: 1 // All observers must implement
2 Public   Interface Iboy {
3//Show the boys the location of light snow, that is, send messages to the observer. The observer can also give feedback on the situation.
4VoidShow (StringAddress );
5}
6 Using System;
7 // Boy A, an observer
8 Public   Class Boya: Iboy {
9 Public   Void Show ( String Address) {
10//Assume that the address is in Korean after processing.
11Console. writeline ("A:"+Address );
12}
13 }
14 Using System;
15 // Boy B, another observer
16 Public   Class Boyb: Iboy {
17 Public   Void Show ( String Address) {
18//Assume that the address is in English after processing.
19Console. writeline ("B:"+Address );
20}
21 }  

Let's take a look at the implementation of light snow, that is, the observer. It mainly looks at the subscribed phone list and how to notify the observer of the message.

Using system;
Using system. Collections. Generic;

Public class GPRS mobile
{
// Save an observer list
Private list <Iboy> boys = NULL;
Private string address = "";
Public uplsmobile ()
{
Boys = new list <Iboy> ();
}
// Add an observer
Public void addboy (Iboy B)
{
Boys. Add (B );
}
Public void removeboy (Iboy B)
{
Boys. Remove (B );
}
// Notification
Private void notify (string address)
{
For (INT I = 0; I <boys. Count; I ++)
{
Boys [I]. Show (Address );
}
}
// Location changed
Public void onaddresschanaged (string newaddress)
{
// Assume that the address is in Chinese format.
Notify (newaddress );
}
}

Observer mode in. net

In. net, Microsoft brings us a better implementation of the observer mode: Event-delegate.

In the gof observer mode (let's call it the classic design mode), the observer must implement a unified interface in.. net ,. the delegate in Net is a safe function pointer (the reason for security is compared with the previous C pointer, C function pointer does not include function signatures, such as parameters, etc, therefore, you can pass a function that is not what you expect, resulting in an error during running. This error occurs during running and is difficult to check ). OK. Now we end today's observer mode with an example of A. Net delegate-event.

Description: This is a console.ProgramThe program receives an integer input between 0 and 100. After the program receives the input, it starts a cycle from 0 to 100. When it loops to the number you enter, it will do some processing, we will describe this instance in two ways, first using the conventional method, and then using the Delegate-event method.

  Public class Program
{
Static void main (string [] ARGs)
{
Console. writeline ("Maid input a 0-100 number :");
Int input = console. Read ();
If (input <0 | input> 100)
{
Console. writeline ("error ");
}
For (INT I = 0; I <= 100; I ++)
{
If (I = input)
{
// Screen output
Console. writeline (I. tostring ());
// A prompt box is displayed.
MessageBox. Show (I. tostring ());
// There may be other operations
}
}
}
}

How do I feel when I see this example? The cyclic code and the processed code are mixed together, and an unknown processing method may be added. The coupling degree is very high. Let's take a look at the. NET processing method.

Namespace observer
{
// Define a delegate. The signature of the observer method is defined here. It is a protocol.
Public Delegate void numbereventhandler (Object sender, numbereventargs E );
// What parameters should be passed to the observer? It is defined here. Note that it must inherit from eventargs
Public class numbereventargs: eventargs
{
Public numbereventargs (INT number)
{
_ Number = number;
}
Private int _ number;

Public int number
{
Get {return _ number ;}
Set {_ number = value ;}
}

}
// Subject in observer Mode
Public class subject
{
// Define an event, that is, the delegated instance.
Public event numbereventhandler numberreached;

Public void dowithloop (INT number)
{
For (INT I = 0; I <= 100; I ++)
{
// The event is triggered
If (I = number)
{
Numbereventargs E = new numbereventargs (I );
Onnumberreached (E );
}
}
}
// Note that this method is defined as protected and virtual, which means that sub-classes can overwrite and change the event triggering behavior.
// You can even not trigger an event
Protected virtual void onnumberreached (numbereventargs E)
{
// Determine whether the event is null, that is, whether the method is bound.
If (numberreached! = NULL)
Numberreached (this, e );
}
}
1

As shown in the code example above, we can sum up the following Rules for The Implementation of The Observer mode: first, the observer must store an observer list. Second, all observers must implement a unified interface.

What are the benefits of the observer model? In the above example, we can see that the observer only depends on a list that implements the observer interface. we can add the observer to this list at any time, however, the observer does not need to pay attention to how the observer is implemented. When we add a new observer to the observer family, the observer does not need to make any changes, and the new type only needs to implement the observer interface.
In the above description, we can see the endless power of interface-oriented programming. Interface-Oriented Programming makes implementation dependent on interfaces, that is, implementation relies on abstraction. In this way, when the dependent object changes, as long as the interface does not change, the dependent object does not need to be changed.

In reality, there are many observer-mode instances. For example, in this era of nationwide stock trading, everyone who holds stocks keeps paying attention to the trend of the stocks they buy. Some people stay in the trading hall every day and watch the trend of stock prices on the screen, some people stare at the computer's stock software during their work hours. For this reason, many companies have adopted various policies to stop such behavior, which not only affects normal work, but also the stock trading hall is often crowded. If there is such a service, as long as you subscribe to a text message, this service will notify you by text message when the stock price you pay attention to changes, in this way, you can do your work in the normal order.

 Public class mainprogram
{
Public static void main ()
{
Console. writeline ("Maid input a 0-100 number :");
Int input = console. Read ();
If (input <0 | input> 100)
{
Console. writeline ("error ");
}

Subject S = new subject ();
// Bind the event method, static
S. numberreached + = new numbereventhandler (msgbox_numberreached );
Mainprogram MP = new mainprogram ();
// Bind the event Method and instance method
S. numberreached + = new numbereventhandler (MP. lele_numberreached );
S. dowithloop (input );
Console. Read ();
}
Void console_numberreached (Object sender, numbereventargs E)
{
Console. writeline (E. Number. tostring ());
}
Static void msgbox_numberreached (Object sender, numbereventargs E)
{
MessageBox. Show (E. Number. tostring ());
}
}
}

Although there are a lot of code in this example, it is worth noting that the event triggering and processing are completely separated, and the loop location no longer needs to know how many methods are waiting to process it.

Summary

Several Design PatternsArticleSome people may think that the design pattern has been trying to solve several problems: decoupling and encapsulation changes. The design model has been striving for maintainability, scalability, and flexibility. Therefore, learning design patterns is not a prototype of understanding design patterns. It is important to understand the scenarios and objectives of design patterns. In this way, you can summarize your own design patterns in your work.
Some people say that mathematics education in China is a mistake. learning mathematics is not just learning those theorem formulas. Learning those things is always behind others. learning mathematics should focus on learning the history of mathematics, following the development history of mathematics, we learned how our predecessors analyzed and solved problems, and learned how their predecessors "fish", not just to get fish ".

I have already written the above article, but today I read an MVP article with a new feeling. I think the above summary is somewhat biased. What's important about the learning model is her essence, but "as a beginner, even if he knows all the design principles, he does not know how to apply them to projects ". Yes, maybe the learning design model should also cause "qualitative change" from "Quantitative Change ". A large number of applications, no matter whether they are overly-designed or not, may be subject to ideological sublimation at a certain time.

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.