Observer mode vs responsibility chain mode

Source: Internet
Author: User
Tags domain name server mx record nslookup nslookup command

Why should we compare the observer mode with the responsibility chain mode? There is not much similarity between the two models. Why not? Similarity exists. We also mentioned the trigger chain (also called the observer chain) in the Observer mode. A specific role can be either an observer or an observer, this forms an observer chain, which is very similar to the responsibility model and implements chain-based transaction processing. For example, when you are asleep during class, the snoring sounds too loud, after covering the voice of the teacher, the teacher got angry and stabbed the principal here. The principal could not handle the problem and complained to your parents. So your devil's day is approaching. This is the responsibility chain model, teachers, principals, and parents are all specific roles in the chain. Events (when you go to bed) are transmitted in the chain and eventually handled by a specific node, and report the results to the caller (You have been beaten ). So what is trigger chain? You are still sleeping in class, or the snoring sound is too loud, the teacher is angry, but the teacher thief is clever and gets out a loudspeaker to give a lecture, so you are not looking for a sleep, at the same time, the ears of other students suffer. This is the trigger chain. The teacher is both the observer (relative to you) and The Observer (relative to other students ), the incident is converted from "you sleep" to "sound amplification" from the instructor. This is also a chain structure, but the events passed in the chain structure have changed.

Let's take a specific example to illustrate the difference between the two. I believe you have heard of the DNS protocol, we only need to set a DNS server address in "Network Settings" to translate the domain name we need into an IP address. The DNS protocol is still relatively simple, pass a Domain Name and record mark (for example, a record or MX record) in the past, and then the DNS starts to look for its own record tree, locate it, and send the IP address to the requester. In the Windows operating system, follow the steps below to learn about the DNS resolution process. In the DOS window, enter the NSLookup Command, as shown in Figure 32-6.

Figure 32-1 DNS domain name resolution

Our intention is to ask the DNS server 192.168.10.1 to parse the IP address of www.xxx.com.cn. How does the DNS server work? That is, the DNS server 18.010.1 in the figure. Does it store the ing between domain names and IP addresses around the world? Impossible. Currently, the number of domain names in the world is 0.17 billion. With such a huge number, each DNS Service stores one copy. How can we quickly respond? DNS resolution response times are generally millisecond-level. How can we make DNS servers blossom everywhere with such high performance requirements? In addition, domain name changes are also very frequent, and the amount of data read and write is also very large. It is impossible to keep one of these 0.17 billion data records for each DNS server. How was that designed? The DNS protocol is still very clever. It stipulates that the DNS server (local DNS) in each region only keeps the domain name resolution in its own region. For domain names that cannot be resolved, then, the system submits the resolution of the higher-level domain name parser, and is finally resolved by a top-level domain name server located in Los Angeles, and returns the result. This is obviously a chain structure processing of a transaction, we use two modes to implement the parsing process.

32.3.1 responsible chain implements DNS resolution process

I guess we can see that this is definitely not the responsibility chain mode. Well, we will use the responsibility chain mode to implement it. First, we will define the business scenario. Here there are three DNS servers: shanghai DNS server (Regional server), China's top-level DNS server (parent server), and Global top-level DNS server, as shown in 22-7.

Figure 32-2 DNS resolution

If a request is sent, it is then resolved by Shanghai DNS. If it can be resolved, the result is returned. If it cannot be resolved, it is submitted to the top-level DNS in China of the parent server for resolution. If it cannot be resolved, it is submitted to the global top-level DNS for resolution. What if it cannot be resolved? The returned domain name cannot be resolved, which may be the domain name of the external planet. Indeed, this is very similar to the responsibility chain model. Let's abstract this process, as shown in the class diagram-8.

Figure 32-3 domain name resolution in the responsible Chain Mode

Let's explain the class diagram. recorder is a bo object that records the DNS resolution results, including the domain name, IP address, and owner (who resolved it ), the getter/setter methods are available. The resolve method in the dnsserver abstract class is a basic method. Each DNS server must have this method. It resolves DNS. How can it be parsed? Specifically, the echo method is used to implement each DNS server. The class diagram is relatively simple. First, let's take a look at the recorder class of the Resolution record, as shown inCodeListing 32-31 is shown.

Code List 32-1 resolution record

Public class recorder {// domain name private string domain; // ip address private string IP; // main private string owner; Public String getdomain () {return domain ;} public void setdomain (string domain) {This. domain = domain;} Public String getip () {return IP;} public void setip (string IP) {This. IP = IP;} Public String getowner () {return owner;} public void setowner (string owner) {This. owner = owner;} // output record information @ overridepublic string tostring () {string STR = "Domain Name:" + this. domain; STR = STR + "\ nip address:" + this. IP; STR = STR + "\ n Parser:" + this. owner; return STR ;}}

Why do we need to override the tostring method? The recorder information can be printed directly for the purpose of printing and displaying. Let's take a look at the abstract Domain Name Server, as shown in the code list 32-32.

Code List 32-2 abstract Domain Name Server

Public abstract class dnsserver {// who is the superior DNS private dnsserver upperserver; // The resolution domain name public final recorder resolve (string domain) {recorder = NULL; If (islocal (domain )) {// The domain name recorder = echo (domain);} else {// This server cannot be resolved // submit the superior DNS for recorder = upperserver resolution. resolve (domain);} return recorder;} // point to the dnspublic void setupperserver (dnsserver _ upperserver) {This. upperserver = _ upperserver;} // each DNS has a DNS data processing zone. Check whether the domain name is protected Abstract Boolean islocal (string domain) in this zone ); // each DNS server must implement the resolution task protected recorder echo (string domain) {recorder = new recorder (); // obtain the IP address recorder. setip (genipaddress (); recorder. setdomain (domain); Return recorder;} // randomly generate an IP address. The tool class is private string genipaddress () {random Rand = new random (); string address = Rand. nextint (255) + ". "+ Rand. nextint (255) + ". "+ Rand. nextint (255) + ". "+ Rand. nextint (255); return address ;}}

There is a method in this class -- genipaddress Method -- which is not displayed in the class diagram. It generates IP addresses randomly. This is a virtual method we have created to simulate DNS resolution scenarios, it is impossible in practical applications. After compiling the abstract DNS server, let's take a look at the specific DNS server. Let's first look at the DNS server in Shanghai, as shown in the code list of 32-33.

Code List 32-3 Shanghai DNS Server

 
Public class shdnsserver extends dnsserver {@ overrideprotected recorder echo (string domain) {recorder = super. echo (domain); recorder. setowner ("Shanghai DNS server"); Return recorder;} // defines the level that the DNS server in Shanghai can process @ overrideprotected Boolean islocal (string domain) {return domain. endswith (".sh.cn ");}}

Why do we need to override the echo method? Each specific DNS server implements its own parsing process and personalized processing. It represents the different processing logic of each DNS server. Note that we have made a simplified process here. All domain names ending with ".sh.cn" are resolved by the Shanghai DNS server. The implementation process of other top-level DNS in China is similar to that of global top-level DNS, as shown in the code list 32-34 and 32-35.

Code List 32-4 top DNS servers in China

Public class chinatopdnsserver extends dnsserver {@ overrideprotected recorder echo (string domain) {recorder = super. echo (domain); recorder. setowner ("Top DNS servers in China"); Return recorder ;}@ overrideprotected Boolean islocal (string domain) {return domain. endswith (". CN ");}}

Code List 32-5 top global DNS servers

 
Public class topdnsserver extends dnsserver {@ overrideprotected recorder echo (string domain) {recorder = super. echo (domain); recorder. setowner ("global top DNS server"); Return recorder ;}@ overrideprotected Boolean islocal (string domain) {// return true for the final resolution location of all domain names ;}}

If all the DNS servers are ready, write a client to simulate how the IP address is resolved, as shown in the code list of 32-36.

Code List 32-6 scenario classes

 
Public class client {public static void main (string [] ARGs) throws exception {// Shanghai Domain Name Server dnsserver SH = new shdnsserver (); // China top-level domain name server dnsserver China = new chinatopdnsserver (); // top-level domain name server dnsserver Top = new topdnsserver (); // define the query path China. setupperserver (top); SH. setupperserver (China); // resolve the domain name system. out. println ("===== domain name resolution simulator ===="); While (true) {system. out. print ("\ n enter the domain name (enter n to exit):"); string domain = (New bufferedreader (New inputstreamreader (system. in ))). readline (); If (domain. repeated signorecase ("N") {return;} recorder = Sh. resolve (domain); system. out. println ("---- DNS Server Resolution result ----"); system. out. println (recorder );}}}

The running result is as follows:

===== Domain name resolution simulator ====

Enter a domain name (enter n to exit): www.xxx.sh.cn

---- DNS Server Resolution result ----

Domain Name: www. xxx.sh.cn

IP Address: 69.224.162.154

Resolved by: Shanghai DNS Server

Enter the domain name (enter n to exit): www. xxx.com.cn

---- DNS Server Resolution result ----

Domain Name: www. xxx.com.cn

IP Address: 51.28.66.140

Resolved by: Top DNS servers in China

Enter the domain name (enter n to exit): www. xxx.com

---- DNS Server Resolution result ----

Domain Name: www. xxx.com

IP Address: 73.247.80.117

Resolved by: World-class DNS servers

Enter the domain name (enter n to exit): n

Please note that the domain name ending with ".sh.cn" is indeed resolved by the DNS server in Shanghai, ". the domain name ending with CN is resolved by top-level DNS in China, and other domain names are resolved by top-level DNS in the world. This simulation process is complete. It is a specific application of the responsibility chain model, put a request to the first node in the chain, and then parse a node in the chain and feed back the caller. Is it perfect?

However, I can tell you responsibly: WHAT ARE THE DEFECTS IN This parsing process? Let's take a look at the next decomposition.

32.3.2 trigger chain to implement DNS resolution process

As mentioned in the previous chapter, it is flawed to use the responsible chain mode to simulate the DNS resolution process. What are the defects? Do you think this parsing process is perfect? It means that you do not know much about the DNS protocol. In this way, we will conduct an experiment, enter the NSLookup command in the DOS window, and then enter multiple domain names, note: what data does the returned value share the same value? By the way, the DNS servers are the same, all of which are resolved by the same DNS server. To be precise, they are all parsed by the DNS server configured on your local machine, this is different from the above simulation process. Let's look at the simulation process. For the requester, ".sh.cn" is resolved by the Regional DNS, ". com "is resolved by the world's top DNS, which is different from the real process. What is the problem?

To be sure, it is imperfect or defective to use the responsible chain mode to simulate the DNS resolution process. How can we fix this defect? Let's take a look at the real DNS resolution process, as shown in 22-9.

Figure 32-4 real DNS resolution

The number ① ② ③ ④ ⑤ in the complete path of a domain name resolution is shown in. First, the requester sends a request, and then the Shanghai DNS Service tries to resolve it, if it cannot be resolved, it is forwarded to top-level DNS in China through path ②. After the resolution, the result is returned to the Shanghai DNS server through path ⑤, and then the Shanghai DNS server returns the result to the requester Through PATH ⑥. Similarly, if top-level DNS in China cannot be resolved, it will be resolved through path ③ to the top-level DNS in the world, and the result will be returned to top-level DNS in China through path ④, then return to Shanghai DNS through Path 5. Note that the number 6th indicates that no matter who resolves the domain name, the requester is still the first node, that is, the first node is responsible for responding to the requester, other nodes do not interact with the requester, but only the left and right nodes of the user. In fact, our DNS server does process this way. For example, if the local request queries a domain name www.abcdefg.com, the Shanghai DNS server cannot resolve this domain name, and then submits it to the top-level DNS server in China, if the top-level DNS server in China has a record of this domain name, the record is found and fed back to the Shanghai DNS server. The Shanghai DNS server performs two transaction processes: the first is the requestor, the second is to store the record for another requestor to query it again, similar to the data cache.

The entire scenario is clear. Let's think about it. We regard the requester as the observer, and its behavior or attribute change notifies the observer Shanghai DNS, shanghai DNS, as an observer, experienced behaviors that could not be handled by itself (behavior changes), notified top DNS in China, and so on. Is it a very standard trigger chain? It must also be a synchronous trigger. asynchronous trigger has lost its meaning in this scenario. You can think about why.

After analyzing so much, we use the trigger chain to simulate the DNS resolution process, as shown in Figure 32-10.

Figure 32-5 trigger chain for DNS resolution

Similar to the responsibility chain mode, there is only one more observable parent class and observer interface, but the implementation of the two is very different. Let's first explain the role of abstract dnsserver, it has two functions.

    • Mark Declaration

It indicates that all DNS servers have dual identities: both the observer and the observer. This is very important. It declares that all servers have the same identities, with this flag, you can move it in the chain without having to fix it in a certain position (this is also an important feature of the chain ).

    • Business Abstraction

The setupperserver method is used to set the parent DNS, that is, to set your own observer. The update method is not only an event handler, but also an event trigger.

Let's look at the code. First of all, the recorder class and the record in the responsibility chain have not changed, so we will not repeat it again. Let's take a look at our core abstraction dnsserver, as shown in code list 32-37.

Code List 32-7 abstract DNS Server

Public abstract class dnsserver extends observable implements observer {// process the request, that is, the public void Update (observable arg0, object arg1) after the event is received {recorder = (recorder) arg1; // if the local machine can parse if (islocal (recorder) {recorder. setip (genipaddress ();} else {// if the local machine cannot be parsed, it is submitted to the dnsresponsfromupperserver (recorder);} // signature sign (recorder );} // as the observer, the observer is allowed to be added. The superior DNS of DNS resolution is generally a public void setupperserver (dnsserver) {// clear the object first, and then add super. deleteobservers (); super. addobserver (dnsserver);} // request resolution from the parent DNS, that is, notify the observer private void responsfromupperserver (recorder) {super. setchanged (); super. notifyobservers (recorder);} // each DNS server signs its own name protected abstract void sign (recorder ); // each DNS server must define its own processing level protected Abstract Boolean islocal (recorder); // randomly generate an IP address, tool class private string genipaddress () {random Rand = new random (); string address = Rand. nextint (255) + ". "+ Rand. nextint (255) + ". "+ Rand. nextint (255) + ". "+ Rand. nextint (255); return address ;}}

Please take a look at the responsefromupperserver method. It only allows setting one observer, because generally DNS services only have one upper-level DNS server, master-slave DNS? I want to know what the primary DNS is and what the standby DNS is, and then ask again! What does the sign method mean? It is the signature. Who parses the record and implements it by each implementation class. The implementation classes of the three dnsservers are relatively simple, as shown in the code list 32-38, 32-39, and 32-40.

Code List 32-8 Shanghai DNS Server

 public class shdnsserver extends dnsserver {@ overrideprotected void sign (recorder) {recorder. setowner ("Shanghai DNS server");} // defines the level at which the DNS server in Shanghai can process @ overrideprotected Boolean islocal (recorder) {return recorder. getdomain (). endswith (".sh.cn") ;}} code list 32-9 China's top DNS server public class chinatopdnsserver extends dnsserver {@ overrideprotected void sign (recorder) {recorder. setowner ("Top DNS servers in China") ;}@ overrideprotected Boolean islocal (recorder) {return recorder. getdomain (). endswith (". CN ") ;}} code list 32-10 world-class top DNS server public class topdnsserver extends dnsserver {@ overrideprotected void sign (recorder) {recorder. setowner ("global top DNS server") ;}@ overrideprotected Boolean islocal (recorder) {// return true for the final resolution location of all domain names; }}

Let's create another scenario class to simulate the DNS resolution process, as shown in the code list of 32-31.

Code List 32-11 scenario

 
Public class client {public static void main (string [] ARGs) throws exception {// Shanghai Domain Name Server dnsserver SH = new shdnsserver (); // China top-level domain name server dnsserver China = new chinatopdnsserver (); // top-level domain name server dnsserver Top = new topdnsserver (); // define the query path China. setupperserver (top); SH. setupperserver (China); // resolve the domain name system. out. println ("===== domain name resolution simulator ===="); While (true) {system. out. print ("\ n enter the domain name (enter n to exit):"); string domain = (New bufferedreader (New inputstreamreader (system. in ))). readline (); If (domain. repeated signorecase ("N") {return;} recorder = new recorder (); recorder. setdomain (domain); SH. update (null, recorder); system. out. println ("---- DNS Server Resolution result ----"); system. out. println (recorder );}}}

Similar to the scenario class in the responsibility chain mode, please note Sh. update (null, recorder) is a virtual observer trigger. The complete method is to take the scenario class as an observed, and then set the observer to the Shanghai DNS server, the test results are the same. Here we use simplified processing to reduce the amount of code. Interested readers can expand the implementation.

Let's take a look at the running results. The results are as follows:

===== Domain name resolution simulator ====

Enter a domain name (enter n to exit): www.xxx.sh.cn

---- DNS Server Resolution result ----

Domain Name: www.xxx.sh.cn

IP Address: 197.15.34.227

Resolved by: Shanghai DNS Server

Enter a domain name (enter n to exit): www.xxx.com.cn

---- DNS Server Resolution result ----

Domain Name: www.xxx.com.cn

IP Address: 201.177.148.99

Resolved by: Shanghai DNS Server

Enter a domain name (enter n to exit): www.xxx.com

---- DNS Server Resolution result ----

Domain Name: www.xxx.com

IP Address: 251.41.14.230

Resolved by: Shanghai DNS Server

Enter the domain name (enter n to exit): n

Check that all the resolution results are returned by the Shanghai DNS server. This is the real DNS resolution process. As you may have said, How do I know whether it is resolved by the Shanghai DNS server or by another DNS server? Easy to do, copy the code, and debug and trace it. It's easy. Or you can take a closer look at the code and understand the code logic.

Let's take a closer look at our code logic. The direct relationship between the upper and lower nodes is very subtle and interesting.

    • Subordinate nodes worship higher-level nodes

For example, the domain name www.xxx.com we entered, the Shanghai Domain Name Server only knows that it is resolved by the parent node (top DNS server in China, the parent node does not know that the request is forwarded to the upper-level node (top-level domain name server). That is to say, the lower-level Node focuses on the response of the upper-level node, as long as it is the result of the superior feedback, it is considered as the superior. The domain name www.xxx.com is eventually resolved by the highest node (the world's top DNS server), it passes the resolution result to the second node (China's top DNS server) when the request is sent to the first node (Shanghai DNS server), the signature is changed to "China Top DNS server ", why? All responses from higher-level nodes are considered to be the results of processing by higher-level nodes, rather than investigating whether the response is actually handled by higher-level nodes.

    • Superior nodes have extreme trust in subordinate nodes

A higher-level node is only responsible for a lower-level node. It does not care where requests from lower-level nodes come from. As long as they are requests sent by lower-level nodes, they are considered as lower-level or www.xxx.com domain names, who does the highest node (the world's top DNS server) consider a resolution request? Of course, it is the second node (top DNS server in China), otherwise it will not report the result to it, but the source of this request is the first node (Shanghai DNS server), trust, it is absolutely trust, and the upper-level node has too much trust in the lower-level node.

Summary

Through the implementation of the DNS resolution process, we found that the trigger chain and the responsible chain are both chain structures, but there are still differences:

    • The message objects in the chain are different.

From the first node to the end node, the message objects transmitted in the two chains are different. The responsibility chain mode basically does not change the structure of the message object, although each node can participate in the consumption (generally not participate in the consumption), similar to the nature of "wild goose feathers", its structure will not change, for example, if a String object or person object is passed in from the first node and does not appear at the end of the chain, it becomes an int or human object, which is impossible in the responsible chain mode, however, in the trigger chain, the objects transmitted in the chain can be freely changed, as long as the upper and lower nodes know about the transmitted objects, it does not require that the message objects in the chain do not change, it only requires that the message objects of two adjacent nodes in the chain be fixed.

    • The relationship between upstream and downstream nodes is different.

In the responsibility chain mode, the upstream and downstream nodes do not have a relationship. They all accept the same object. All the transmitted objects are delivered from the first part of the chain. The last node is a cat and a dog and it has nothing to do with me, I only need to process it according to my own logic. The trigger chain is different. The relationship between superiors and subordinates is very close. The subordinates worship the superiors and the superiors absolutely trust the subordinates. Any two adjacent nodes in the chain are a solid and independent group.

    • Different message distribution channels

In the responsibility chain mode, after a message is transmitted from the beginning of the chain, it starts to move along the chain to the end of the chain. The direction is single and fixed, while the trigger chain is different, because it uses the observer mode, it can have a great deal of flexibility. After a message is passed to the first part of the chain, it is not fixed. It can be transmitted in broadcast mode, you can also skip the transfer, depending on the message processing logic.

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.