Design pattern question and answer (II.)

Source: Internet
Author: User

What is the interpreter mode?

The interpreter pattern allows semantics to be interpreted into a code solution. Let's take a look at the specific meanings below. The syntax is mapped to a class to apply to the solution, for example, 7-2 can be mapped to the ' Clsminus ' class. The first-line interpreter pattern gives us a scenario of how to write an interpreter in which the interpreter can read and execute the syntax in code. For example, in the example below we give a date formatting syntax, where the interpreter gives the converted code solution and outputs the desired result.


Figure 1: Date syntax

Let's write a date format interpreter as shown in "Date syntax". Before we begin we need to understand the different components in the interpreter pattern, and then we will map the same syntax. The context contains data, and the logical part contains the logic to convert the context into a readable format.


Figure 2: Context and logic

Now let's look at the syntax in date formatting. Before we define any syntax, we first divide the syntax into small logical blocks. The figure "Syntax mapping to class" shows how different components are determined, and then mapping to the syntax of the class is only part of the implementation of the complete syntax. So we split the date formatting into 4 components month, day, year, and delimiter; For these four components we define different classes to contain their own logic, as shown in "syntax mapping to Classes". Therefore, we will create different classes for the 4 different components in the date format.


Figure 3: Syntax mapping to classes

As mentioned earlier, there are two classes where one is an expression class that contains logic and the other is a context class that contains data, as shown in expressions and context classes. We define different resolutions in different classes, all of which inherit from the ' Clsabstractexpression ' interface, which contains the ' Evaluate ' method; The Evaluate ' method holds a context class containing data and parses the data through expression logic. For example ' clsyearexpression ' will replace ' YYYY ' with the year, ' Clsmonthexpression ' will replace ' MM ' with month and so on.


Figure 4: Interpreter pattern class diagram


Figure 5: Expressions and Context classes

Now that we have encapsulated the expression parsing logic in different classes, let's look at the client usage logic. The client first passes the date formatting syntax to the context class, and according to the date formatting we add the presentation class to a collection. For example, when a "DD" expression is found, the ' clsdayexpression ' is added, and the ' Clsmonthexpression ' class is encountered when encountering the ' MM ' expression, and so on. Finally we loop through the ' Evaluate ' methods of these classes. When all of the classes are called, we get the display results.


Figure 6: Client Utility interpreter Code logic

What is an iterator pattern?

The iterator pattern allows sequential access to elements without exposing internal code. The specific meanings are as follows. The iterator pattern is what we need, assuming that there is a collection of records, and we want to sequentially browse these combinations and also want to save the location of the currently browsed records. This pattern is the most common and often unintentionally used pattern. We are using the iterator pattern to a certain extent in all of the loops that use ' foreach ' (which allows a set of sequential loops).


Figure 7: Iterator Mode business logic

In the figure "Iterator Mode business logic" We define a class ' Clsiterator ' that contains a collection of customer classes. So we first defined a ArrayList and a ' fillobjects ' method in ' Clsiterator ' to populate the data for ArrayList. This consumer collection ArrayList is private, and customer data can be found through subscripts in the collection. So we open the ' Getbyindex ' method (by specifying the subscript to find the element), the ' Prev ' method (get the previous element in the collection), ' Next ' method (get the next element in the collection), ' GetFirst ' method (get the first element in the Union), ' GetLast ' method (Gets the last element in the collection).

The client sees only these methods, which are used to sequentially access the collection and to remember the subscript that has been visited.

The client uses iterator mode logic to show how to use the next, previous, last, first functions in ' Clsiterator ' and specify subscripts to create the ' Objiterator ' object.


Figure 8: The client uses the iterator pattern logic

What is the mediator model?

Many times the communication between components in a project is very complex because of the complexity of calls between components. The mediator pattern helps the object communicate in an unrelated way, which minimizes complexity.


Figure 9: A simple example of a mediator pattern

Let's consider the case in the "simple example of a mediator pattern", which describes a situation in which a mediator pattern is needed in a real-world scenario. It is a very user-friendly interface; It has 3 typical scenarios:

Scenario 1: You need to turn on the Add button and the empty button when the user enters text in the text box. In this example, the text box is empty, and the Add and empty buttons need to be disabled at this time.


Figure 10: Scene 1

Scenario 2: When the user clicks the Add button, the data should go into the list box. Once the entry is entered into the list box, the system needs to empty the text box and disable the Add and clear buttons.


Figure 11: Scene 2

Scenario 3: If the user clicks the Clear button the system should empty the text box and disable the Add and clear buttons.


Figure 12: Scene 3

From the UI interface in Scenario 3, you can see how complex the interaction between these UIs is. "Complex interactions between components" demonstrates the complexity of logic.


Figure 13: Complex interactions between components

Then we look at "the mediator's use of a simplified figure". Each component is not directly interactive, but rather interacts with a centralized component such as a mediator, where the mediator pays attention to sending the message to other components, so that the logic becomes clean and clear.


Figure 14: The mediator uses a simplified diagram

Let's look at how the code is written. We will use C # but you can easily convert it to Java code or other languages. The full code of the mediator class shown by the "Mediator class".

The first thing a mediator class does is hold a reference to a complex interaction-related class. So here we open 3 overloaded methods called ' register '; ' register ' Holds text box objects and button objects; the interaction of scenes is concentrated in ' Clickaddbutton ', ' textchange ', ' Clickclearbutton ' method, these methods will enable and disable the relevant UI based on different scenarios.


Figure 15: Mediator Class

The client code is very neat at the same time. In the constructor, you first register all the components that need to interact with the Mediator class, and then you only need to invoke the Mediator class method for each scenario. In short, we call the ' TextChange ' method of the Mediator class when the text changes, and call the ' Clickaddbutton ' method when the user clicks the Add button, and call the ' Clickclearbutton ' method when the user taps the empty button.


Figure 16: Mediator Mode client logic

What is Memo mode?

The memo mode provides a way to provide the internal state of the captured object without destroying the package. It helps to store snapshots of objects so that they can be queried at any time. Let's look at what it means in a real-world scenario. A customer screen is shown in the memo mode practice example, assuming that the user starts editing a customer record and makes some changes; after a while the user feels that the operation is wrong and wants to revert to the original data, which is the appropriate scenario for the memo pattern. It helps us to store a copy of the data and revert to the original state when the user clicks Cancel.


Figure 17: Example of a memo pattern practice

Let's try using C # to complete the example of the customer UI we just discussed. The following is the customer class ' Clscustomer ', which aggregates the memo class ' Clscustomermemento ' that stores a snapshot of the data. Where memo class ' Clscustomermemento ' is explicitly used to replicate customer classes (excluding methods) ' Clscustomer '; When consumer class ' Clscustomer ' Initialization, the memo class is also initialized, and when the customer class data changes, the snapshot in the memo class does not change, where the ' Revert ' method can restore the data in the memo to the main class.


Figure 18: The Customer class in the memo

The client code is very simple. Create a customer class, and once there is a problem we can click the Cancel button to call the ' revert ' method to restore the data to the snapshot data in the memo. This logic is shown in the "Memo client code" diagram.


Figure 19: Memo Client code

What is the Observer pattern?

The observer pattern helps us to complete communication between the parent class and the classes that are related to or dependent on him. There are two more important concepts of ' Subject ' (subject) and ' observers ' (Observer). Subject (subject) When you send a notification, you will receive a notification if the viewer registers with the topic. "Subject and observers" shows the app (subject) Sending notifications to all observers (email, event log, SMS). We can also encapsulate this example as a publish/subscribe model; The publisher is the app, and the Subscriber is the email, event log, SMS.


Figure 20:subject and observers

Next we'll try the simple example code we defined in the previous section. First, let's look at the Subscriber/notification class first. The figure "Subscriber class" shows the code, which defines a unified interface such as ' Inotification ' for all subscribers, which has a ' notify ' method. This interface is implemented by all specific notification classes, and all notification classes define their own notification methods. For the current scenario, we just display a printed string to indicate that a particular method is being executed.


Figure 21: Subscribers ' classes

As shown earlier, the observer pattern is divided into two parts, one of which is the observer/subscriber, as we mentioned before, and the other is the Publisher or topic.

The publisher has a collection to hold all subscribers who need to be notified. By using ' addnotification ' and ' removenotification ' you can add or remove subscribers from the collection, and use the ' Notifyall ' method to cycle through all subscribers to send notifications.


Figure 22: Publisher/Subject Class

Now that we've seen the release and subscriber classes, let's take a look at the client code and see how the viewer behaves. The following is an observer client code fragment. First, create a Notifier object that has a collection of subscribers, and then add the Subscribers that need to be notified to the join. The logic at this point is that if the customer's code is longer than 10 characters, all Subscribers are notified.


Figure 24: Observer mode client code



1. This article is translated by the programmer architecture

2. This article is translated from

Http://www.codeproject.com/Articles/28359/Design-pattern-FAQ-Part-Design-pattern-training

3. Reprint please be sure to indicate this article from: Programmer Architecture (No.:archleaner )

4. More articles please scan the code:

Design pattern question and answer (II.)

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.