C # design mode seven-adapter mode (Adapter) "Structural"

Source: Internet
Author: User

First, Introduction

From today onwards we begin to talk about "structural" design patterns, "structural" design patterns are as follows: Adapter mode, bridge mode, decorative mode, combination mode, appearance mode, enjoy meta-mode, proxy mode. The "created" design pattern solves the problem of object creation, and the "structured" design pattern solves the problem of the combination of classes and objects. Today we start talking about the first design pattern in the "structural" design pattern, the adapter pattern. Speaking of this model is actually very simple, in real life there are many examples, such as: Our phone charger, charger connector, some of the two-phase electricity into three-phase electricity, of course, there are three-phase electricity into two-phase electricity. We often use laptops, laptop operating voltage and our home lighting voltage is inconsistent, of course, the charger will need to convert the lighting voltage to the operating voltage of the notebook, only so that the laptop can work properly. Too many, not all listed. We just have to remember that adaptation is a transformation that transforms two things that can't work together, so that they can work together.

second, detailed introduction of the adapter mode

2.1. Motive (motivate)

In the software system, because of the change of the application environment, it is often necessary to put "some existing objects" in the new environment, but the interfaces required by the new environment are not satisfied by these existing objects. How do you deal with this "migration change"? How can you take advantage of the good implementations of existing objects while satisfying the interfaces required by the new application environment?

2.2. Intention (Intent)

Convert the interface of one class into another interface that the customer wants. The adapter mode makes it possible for those classes that would otherwise not work together because of incompatible interfaces to work together.

2.3. Result Diagram

The adapter has two types of structure

   -Object Adapter ( more commonly used )



The object adapter uses a scheme of object composition, and its adapter kernel adaptee relationship is a composite relationship.

The combination mode is preferred in Oo, and the combination mode is not suitable for inheriting. Because the composition mode is more loosely coupled, and inheritance is tightly coupled, any changes to the parent class cause a change in the subclass.

   -Class Adapter



2.4, the composition of the model

. Target role: Defines the interface that the client uses for a specific domain.

. Customer role (client): Works with objects that match the target interface.

. Adaptive Role (Adaptee): Defines an interface that already exists and is already in use, and this interface needs to be adapted.

. Adapter Role (ADAPTE): The core of the adapter mode. It converts the interfaces that are already present in the Adaptee role to the target role targets matching interfaces. The interface to the Adaptee is adapted to the target interface.

2.5 Specific implementation of adapter mode

Because there are two implementations of the adapter pattern, today we have implemented our own approach for each of them.

1, the object is the adapter mode implementation

1 namespacethe adapter mode of the object2 {3     ///<summary>4     ///Home Only two holes of the socket, also too lazy to buy power strip, but also to spend money, but my phone is a 3 small pillars of the plug, obviously directly do not, it is appropriate to match it5     ///</summary>6     classClient7     {8         Static voidMain (string[] args)9         {Ten             //Okay, now we can charge the phone. OneTwohole Hometwohole =NewThreetotwoadapter (); A hometwohole.request (); - console.readline (); -         } the     } -   -     /// <summary> -     ///my family has only 2 holes in the socket, which is the target role in the adapter mode, which can be written as abstract class or interface +     /// </summary> -      Public classTwoholetarget +     { A         //methods required by the client at          Public Virtual voidRequest () -         { -             //you can put the general implementation here -         } -     } -   in     /// <summary> -     ///The phone charger is a plug with 3 pillars, the source role-the class that needs to be adapted (Adaptee) to     /// </summary> +      Public classThreeholeadaptee -     { the          Public voidspecificrequest () *         { $Console.WriteLine ("I'm a 3-hole plug.");Panax Notoginseng         } -     } the   +     /// <summary> A     ///Adapter class, Twohole This object written as an interface or abstract class is better, interface-oriented programming the     /// </summary> +      Public classThreetotwoadapter:twoholetarget -     { $         //reference to an instance of two hole plugs to connect the client to the Twohole $         PrivateThreeholeadaptee threeholeadaptee =Newthreeholeadaptee (); -         //here, you can continue to add the appropriate objects.  -   the         /// <summary> -         ///implementation of 2-hole Plug interface methodWuyi         /// </summary> the          Public Override voidRequest () -         { Wu             //can do a specific conversion work - threeholeadaptee.specificrequest (); About             //can do a specific conversion work $         } -     } -}


2, Class of adapter mode implementation

1 namespaceAdapter mode of design mode2 {3     /// <summary>4     ///here is the case of mobile phone charger, our home socket is two-phase electricity, but the phone socket connector is three-phase electricity5     /// </summary>6     classClient7     {8         Static voidMain (string[] args)9         {Ten             //Okay, now it's ready to recharge. OneItwoholetarget change =NewThreetotwoadapter (); A Change . Request (); - console.readline (); -         } the     } -   -     /// <summary> -     ///my family has only 2 holes in the socket, that is, the target role in the adapter mode (target), which can only be the interface, but also the restrictions of the class adapter +     /// </summary> -      Public InterfaceItwoholetarget +     { A         voidRequest (); at     } -   -     /// <summary> -     ///plug for 3 holes, source role-class to be adapted (Adaptee) -     /// </summary> -      Public Abstract classThreeholeadaptee in     { -          Public voidspecificrequest () to         { +Console.WriteLine ("I'm a three-hole plug."); -         } the     } *   $     /// <summary>Panax Notoginseng     ///adapter class, the interface to be placed behind the class, there is no suitable for more objects, this is the lack of class adapter -     /// </summary> the      Public classThreetotwoadapter:threeholeadaptee,itwoholetarget +     { A         /// <summary> the         ///implementation of 2-hole Plug interface method +         /// </summary> -          Public voidRequest () $         { $             //Call 3 Hole plug Method -              This. Specificrequest (); -         } the     } -}

   Code are very simple answer, anyone can understand, there are detailed notes.

Third, the implementation of the adapter mode key points:

The adapter mode is mainly used in cases where "it is desirable to reuse some existing classes, but the interface is inconsistent with the reuse environment", which is useful in legacy code reuse, class library migration, and so on.

GOF23 defines the implementation structure of the two adapter modes: Object adapters and Class adapters. Class adapters are implemented in a "multi-inheritance" way, in the C # language, if the matching role is a class, the implementation of target can only be an interface, because the C # language supports only the multiple inheritance attributes of the interface. In the C # language, the class adapter is also difficult to support the case of multiple objects, but also bring bad high coupling and violate the principle of a single class, it is generally not recommended. The object adapter uses the "Object Combination" way, more in accordance with the loose coupling spirit, the adaptation of the object is not limited, can be one or more, but makes it difficult to redefine the behavior of Adaptee, This requires generating a subclass of Adaptee and making adapter reference this subclass instead of referencing Adaptee itself. The adapter pattern can be implemented flexibly without having to stick to the two structures defined in the GoF23. For example, the "existing object" in adapter mode can be used as a new interface method parameter to achieve the purpose of adaptation.

The adapter pattern itself requires us to use the "interface-oriented programming" style as much as possible, so that it can be easily adapted later.

Adapter mode is used to solve the problem that the existing objects and clients expect interface inconsistency, the following details the advantages and disadvantages of the two forms of adapter.

Iv. implementation of adapter patterns in. NET

said that the implementation of the adapter mode in NET is many, such as: System.IO inside many classes have the adapter shadow, when we manipulate the file, in fact, called the COM interface implementation. The following two points are also examples of adapter use:

1. Reusing COM objects in. NET:

COM objects do not conform to the interfaces of. NET objects and use Tlbimp.exe to create a runtime callable Wrapper (RCW) that conforms to the interfaces of. NET objects, and COM interop is like a bridge between COM and. Net.

2..NET data Access Class (adapter variant):

Various databases do not provide a DataSet interface, and with DbDataAdapter you can adapt any database access/access to a DataSet object, DbDataAdapter a good fit between a database and a dataset. Of course there is the SqlDataAdapter type, and the database for Microsoft SQL Server type is adapted to and from the dataset.

v. Summary

Today's article is written here, before the end of today's writing, there is a sentence to say, although previously said. Each design pattern has its own application scenario, it is to solve a class of problems, there is no so-called shortcomings, no design pattern can solve all situations. The way we use design patterns is through continuous refactoring to use patterns, not to use design patterns, for patterns and patterns. If the software does not have a change in demand, we do not have a problem with the pattern. In case of problems, we write according to the routine, with the change of demand, then we go to abstract, understand the use of the scene, and then choose the appropriate design pattern.

C # design mode seven-adapter mode (Adapter) "Structural"

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.