C # design mode (7) -- Adapter mode (Adapter Pattern)

Source: Internet
Author: User

I. Introduction

In the actual development process, due to the changes in the application environment, such as the changes in the use language), we need to implement that there is no existing object in the new environment to meet, however, such existing objects exist in other environments. So what if we call "existing objects" in the new environment? The solution to this problem is the adapter mode we will introduce in this article --In this way, existing implementations do not need to be repeated in the new environment, so that existing objects can be referred to existing objects in the original environment .).

Ii. detailed introduction to the adapter mode 2.1 Definition

Next let's take a look at the adapter definition. The adapter mode -- converts an interface of a class into another interface that the client expects, so that the two classes that cannot work together because the original interface does not match can work together. The adapter mode can be a class adapter mode or an Object Adapter mode, the following describes the implementation of these two forms and provides corresponding class diagrams to help you clarify the relationship between classes.

2.2 class adapter mode implementation

Here, we use an example in our daily life to demonstrate the implementation of the adapter mode. The specific scenario is: in our daily life, the electrical plug we bought has two holes, however, the outlet we bought only has three holes. At this time, we hope that the electrical plug can be converted into three holes, so that we can directly insert it into the outlet, at this time, the three-hole plug is another interface that the client expects. Naturally, the two-hole plug is the existing interface, and the adapter mode is used to complete this conversion. The specific implementation code is as follows:

Using System; // The following uses a socket and a plug as an example to describe the adapter mode. // The electrical plug we purchased now has two holes, however, the outlet we purchased only has three holes. // This is the adapter mode in which we want to plug the electrical appliance into the outlet. {// <summary> /// client, the customer wants to convert the two-hole plug into the three-hole plug, and hand the switch over to the adapter. // Since the adapter needs to complete this function, so it must have two specific hole plug and three hole plug features at the same time // </summary> class Client {static void Main (string [] args) {// now the client can use the IThreeHole threehole = new PowerAdapter (); threehole through electrical adaptation. request (); Console. readLine () ;}//< summary> /// three-hole plug, that is, the target role in the adapter mode /// </summary> public interface IThreeHole {void Request () ;}/// <summary> /// plug in two holes, source role -- the class to be adapted // </summary> public abstract class TwoHole {public void SpecificRequest () {Console. writeLine ("I Am a plug with two holes") ;}/// <summary> /// adapter class, the interface should be placed behind the class. // The adapter class provides three hole plugs, but its essence is to call the method of two hole plugs. // </summary> public class PowerAdapter: twoHole, IThreeHole {// <summary> // method for implementing the three-hole connector interface /// </summary> public void Request () {// call the two-hole connector method this. specificRequest ();}}}

From the code above, we can see that the client wants to call the Request method, that is, the three-hole plug), but our existing class is the two-hole plug.) There is no Request method, it only has the SpecificRequest method, that is, the two-hole plug method), but the adapter class adapter must implement the three-hole plug interface and inherit the two-hole plug class) can provide this conversion, it provides the Request method to implement the internal call of the two hole plug, because the adapter is only a shell, packed with two hole plug because only in this way, electrical appliances can use ), and provide the appearance of the three-hole plug to the outside world) for the client.

2.3 class diagram

In the above implementation, because the adapter PowerAdapter class) and the source role TwoHole class) are inherited, so the adapter mode is the adapter mode of the class, the specific class diagram is:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/124A13514-0.png "style =" margin: 0px auto; padding: 0px; border: 0px; "alt =" 12084713-b5d34de6c7bda-4c9640a45a64215a5 "/>

2.4 Object Adapter Mode

The above is an introduction to the class adapter mode. However, the adapter mode also has another form-the Object Adapter mode. Here we will explain its implementation and implementation analysis ideas: now, the adapter class cannot inherit the TwoHole abstract class, because the inheritance class belongs to the class adapter), but the adapter class must implement the method that the client expects, that is, the Request method, therefore, the ThreeHole abstract class or the IThreeHole interface must be inherited. However, the Request method of the adapter class must call the SpecificRequest method of TwoHole and cannot be inherited, however, we can create a TwoHole object in the adapter class and then use the TwoHole method in Requst. As we have analyzed, the implementation of the object's adapter mode is formal. The following shows the specific implementation code:

Adapter mode of the namespace object {class Client {static void Main (string [] args) {// now the client can use the ThreeHole threehole = new PowerAdapter (); threehole through electrical adaptation. request (); Console. readLine () ;}//< summary> /// three-hole plug, that is, the Target in the adapter Mode) role /// </summary> public class ThreeHole {// method required by the client public virtual void Request () {// you can put the general implementation here} // <summary> // two-hole plug, source role -- the class to be adapted // </summary> public class TwoHole {public void SpecificRequest () {Console. writeLine ("I Am a plug with two holes") ;}/// <summary> /// adapter class. The adapter class does not have the TwoHole class, /// the TwoHole object is referenced, so it is the implementation of the object's adapter mode. /// </summary> public class PowerAdapter: ThreeHole {// reference instances with two hole plugs, so as to associate the client with TwoHole public TwoHole twoholeAdaptee = new TwoHole (); /// <summary> /// method for implementing the three-hole connector interface /// </summary> public override void Request () {twoholeAdaptee. specificRequest ();}}}

From the code above, we can see that the object's adapter mode is implemented just as we started to analyze. The client calls the code and the class's adapter implementation are basically the same, next let's take a look at the class diagram of the object's adapter mode. The specific class diagram is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/124A110A-1.png "style =" margin: 0px auto; padding: 0px; border: 0px; "alt =" 13091027-628ae240658d4a8192bc16903f83898 "/>

Iii. Advantages and disadvantages of the adapter Mode

As mentioned in the introduction, the adapter mode is used to solve the problem that the existing object is inconsistent with the client's expected interface. The advantages and disadvantages of the two methods are summarized in detail below.

Class adapter mode:

Advantages:

  • The existing class can be reused without modifying the original code, which is well compliant with the "open and closed principle"

  • Partial behavior of Adaptee (adapted class) can be redefined, because Adapter is a subclass of Adaptee in class Adapter mode.

  • Introducing only one object does not require additional fields to reference Adaptee instances. This is both an advantage and a disadvantage ).

Disadvantages:

  • Use a specific Adapter class to match Adaptee and Target. If you want to match a class and all its subclasses, the Adapter mode of the class is not competent. Because the Adaptee instance is not introduced in the adapter mode of the class, it is impossible to call the SpecificRequest method of the corresponding subclass by simply calling this. SpecificRequest method.

  • The implementation of "Multi-inheritance" brings about poor high coupling.

Object Adapter Mode

Advantages:

  • The existing class can be reused without modifying the original code, which is well compatible with the "open and closed principle". This is achieved in both methods)

  • The "Object combination" method is adopted, which is more compliant with loose coupling.

Disadvantages:

  • This makes it difficult to redefine Adaptee, which requires generating a subclass of Adaptee and making the Adapter reference this subclass instead of referencing Adaptee itself.

Iv. Use Cases

You can consider using the adapter mode in the following situations:

  1. The system must reuse existing classes, and the interfaces of these classes do not meet the requirements of the system.

  2. You want to create a reusable class for some classes that are not highly correlated with each other, including some classes that may be introduced in the future.

  3. For the Object Adapter mode, you need to change multiple existing subclass interfaces in the design. If you use the class adapter mode, you need to create an adapter for each subclass, which is not practical.

V. Implementation of the adapter mode in. NET

1. One of the biggest applications of the adapter mode in. NET Framework isCOM Interop. COM Interop is like a bridge between COM and. NET. For more information about COM interoperability, refer to my interoperability series ). COM Component Object and. NET class object are completely different, but to make the. NET Program

Using COM components like using. NET objects, Microsoft uses the Adapter mode in terms of processing methods to encapsulate COM objects. This packaging class is RCW (Runtime Callable Wrapper ). RCW is actually a. NET class generated by runtime. It encapsulates the methods of the COM component and internally calls the COM component. As shown in:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/124A12630-2.png "style =" margin: 0px; padding: 0px; border: 0px; "alt =" 13235508-4288d25e62b7490bb4e2916ca0deaef "/>

2. Another adapter mode application in. NET isDataAdapter. ADO. NET provides multiple interfaces and classes for Unified Data Access. One of the most important interfaces is IdataAdapter. DataAdpter acts as the database-to-DataSet bridge, so that data operations of applications are unified to DataSet, regardless of the specific database type. You can even compile your own DataAdpter for special data sources to make our applications compatible with these special data sources.

Vi. Summary

The introduction of the adapter mode is over. This article mainly introduces the implementation of the adapter mode, analyzes their advantages and disadvantages, and introduces the use cases. In the adapter mode,The Adapter can be an abstract class, and the implementation of the Adapter mode is very flexible.The "existing object" in the mode serves as the new interface method parameter. The adapter class can return a suitable instance to the client based on the parameter parameters.


This article is from the "LearningHard" blog, please be sure to keep this source http://learninghard.blog.51cto.com/6146675/1308323

Related Article

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.