Design Pattern Quiz (iii)

Source: Internet
Author: User
Tags parse string

What is a state mode?

State mode allows an object to determine its behavior based on the value of the current object. such as "state mode example" is an example of a light bulb operation. If the status of the light is off, the state will turn on when the switch is pressed, or if the switch is on, press the switch light off. In short, the behavior varies depending on the state.

Figure 1: Example of a state pattern

Here we try to implement the example using C #. The figure "State mode practice" shows the business class and client code. We created a class ' clsstate ' that contains two state "on" and "Off" enumerations, and also defines the ' Pressswitch ' method, which toggles state based on the current state. In the right half of the diagram we implement a client that uses the class ' Clsstate ' to invoke the ' Pressswitch method, and use the ' GetStatus ' method to display the current state in a text box.

When we click, the current state is switched back and forth.

Figure 2: State mode Practice

What is a policy model?

The policy pattern encapsulates the algorithm in a class and can be interchanged according to the classes used. This pattern is useful when we want to decide which algorithm to use at run time.

Let's look at an example of how a policy pattern works. We take the addition and subtraction of mathematical operations as an example, the diagram "strategy mode Practice" shows the logic. It receives a number as a parameter, giving different results depending on the strategy. Therefore, if you are using an addition strategy, then two numbers will be added, and if you are using a subtraction strategy, the two numbers will be subtracted. These strategies are just algorithms. The policy pattern is also just encapsulation of the algorithm.

Figure 3: Policy Mode Practice

The first thing we need to know is how these algorithms are encapsulated in a class. The "algorithm encapsulation" shows how the "add" algorithm is encapsulated in the ' Clsaddstatergy ' class, the ' substract ' algorithm is encapsulated in the ' Clssubstractstatergy ' class, and these classes are inherited from ' Clsstratergy ' class, which provides a ' calculate ' method for subclasses.

Figure 4: Algorithm encapsulation

Then define the wrapper class ' clsmaths ' to refer to the ' Clsstatergy ' class and set the policy class to be used by ' setstatergy '.

Figure 5: Policy classes and their wrapper classes

The policy mode calling code shows the usage of the wrapper class and sets the policy at run time through the ' Setstatergy ' method.

Figure 6: policy mode call code

What is the visitor pattern?

The visitor pattern allows you to modify the class structure without changing the actual class. It is a way to separate logic and algorithms from the current issue structure. In this way we can add new logic to the current data without modifying the structure, and on the other hand, we can modify the data structure without touching the logic.

"Logic and data Structure" contains a consumer data structure, each consumer object has multiple address objects, and each address object has multiple phone objects. This data structure needs to be presented in two different formats: String, XML. So we need to write two classes one is a string-related logical class and the other is an XML-logical-related class. These two classes traverse the object structure and give the corresponding output. In short, the visitor contains logic.

Figure 7: logic and data Structures

Then we use C # to implement the above example. Other programming languages have the same empathy. We created a single visitor class to parse string logic and XML separately. Each of the two classes has a visit method to parse the corresponding object. These classes implement a ' ivisitor ' universal interface to maintain unity.

Figure 8: Visitor Class

The previously defined visitor class is passed to the data structure class, such as the consumer class. So, in the consumer class, we pass in the visitor class in the ' Accept ' function. In this method we call the visit method by passing the type of the visitor class, and the visit method is overloaded, so it determines which method to invoke based on the type of the parameter class being passed.

Figure 9: Passing the visitor class to the data structure

Because each consumer has multiple addresses, each with multiple phone objects, the ' Objaddresses ' collection is integrated in the ' Clscustomer ' class, and the ' Objphones ' collection is integrated in the ' Clsaddress ' class. Each object has an accept method and holds the visitor class object and resolves itself in the visit method in the visitor class. Because the visit method is overloaded, it will call the appropriate method polymorphic.

Figure 10: Consumer, address, phone object

Now that we have defined the logic of the visitor class and the internal data structure of the consumer class, we can then use them on the client. Visitor Mode client code shows a code snapshot that uses the visitor pattern. First, the visitor object is created and passed to the consumer data class, and if we want to present the consumer object data structure as a string, create ' clsvisitorstring ' and if you want to present it in XML format, create a ' Clsxml ' object and passes it to the consumer object data structure. We can easily understand this logic from the data structure.

Figure 11: Visitor Mode client code

What is the difference between the visitor pattern and the policy mode?

The visitor pattern and the policy pattern look very similar because they encapsulate the responsible logic from the data. It can be said that the visitor pattern is a common form of the policy pattern. In policy mode, there is a context or a single logical data object on top of multiple algorithms. In the previous question we explained the rationale for the strategy pattern and the visitor pattern, so let's look again at the examples we've already understood. There is a single context class and multiple algorithms in the policy mode. The figure "policy mode" shows how the context class and multiple algorithms work in harmony.

Figure 12: Policy mode

The visitor pattern has multiple context objects, and each context object contains an algorithm. In the visitor pattern example we have written examples of parsing data such as consumers, addresses, phone objects.

Figure 13: Visitor Mode

So, in short, the strategy pattern is a special form of the visitor pattern. In the policy mode, all algorithms have only one context and the visitor pattern has a context for each algorithm object. So the basic criteria for choosing whether to use the policy mode or the visitor pattern is the relationship between the context and the algorithm. If you need a context, multiple algorithms, select the policy mode, and if you have multiple contexts and algorithms, choose to use the visitor pattern.

What is adapter mode?

Many times two classes become incompatible because they inherit from incompatible interfaces. The adapter pattern helps us to wrap the existing classes so that the two classes become compatible with each other. Both collections in incompatible interfaces hold a string value; they all have a way to add a string to the collection; One method is ' Add ' and the other is ' Push '; one uses the collection object and the other uses the stack. We want to make the stack object and the collection object compatible.

Figure 14: Incompatible interfaces

There are two ways to implement the adapter pattern, one is aggregation (this is called the object adapter pattern), and the other is inheritance (this is called Class adapter mode). First, let's look at the object adapter pattern.

The object adapter pattern shows a broad approach to implementation. In this example we introduce a new wrapper class ' Clscollectionadapter ', which wraps the ' Clsstack ' class and includes the push method in the Add method, which makes the two classes compatible.

Figure 15: Object Adapter Mode

Another way is to use inheritance to implement adapter mode, also known as Class adapter mode. The figure "Class adapter Mode" shows how class ' Clsstack ' makes compatible ' clscollection ' classes by inheriting ' Clscollectionadapter '.

Figure 16: Class adaptation mode

What is the enjoy meta mode?

This is useful when we need to create many objects and share the same data when these objects are shared. objects and shared data, we need to print business cards for all employees in the organization so that we have two parts of data, one is variable data, such as employee name, and the other part is static data such as address. You can minimize memory usage by preserving only one copy of the static data and making all Mutable objects reference that address. So we create different mutable data but all reference the same static data, which optimizes the use of memory.

Figure 17: Objects and common data

The following is a C # code instance of the enjoy meta pattern. There are two classes: ' Clsvariableaddress ' to save the Dynamic Data, ' clsaddress ' to save the static data, to ensure that the ' clsaddress ' class has only one instance, we created a wrapper class ' clsstatic ' and ' Static instance of the Clsaddress ' class. This class aggregates the ' Clsvariableaddress ' class.

Figure 18: Class diagram of the enjoy meta-mode

In the "Enjoy meta-mode client code" we created two objects of the ' Clsvariableaddress ' class, but the internal static data, such as the address class, has only one instance.

Figure 19: Enjoy meta-mode client code



1. This article is translated by the programmer architecture

2. This article is translated from http://www.codeproject.com/Articles/28384/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 Quiz (iii)

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.