NET design Pattern Part III Structural mode (7): Adapter mode (Adapter pattern)

Source: Internet
Author: User

Adapter mode (Adapter pattern)

——. NET design Pattern series eight

TERRYLEE,2006 year February

Overview

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. So 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? This is the adapter model to be said in this paper.

Intention

Transforms 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.

Structure diagram

Figure 1 Adapter pattern structure diagram of the class

Figure 2 Adapter schema structure of the object

Examples of life

The adapter mode allows the interface of one class to be converted to another interface that the customer expects, so that classes that cannot work together because of incompatible interfaces can work together. The wrench provides an example of an adapter. A hole is set on the ratchet, and the size of each side of the ratchet is the same. Typical side length in the United States are 1/2 "and 1/4". Obviously, if you do not use an adapter, the 1/2 "Ratchet cannot fit into a 1/4" hole. A 1/2 "to 1/4" adapter has a 1/2 "recess to cover a 1/2" tooth, while there is a 1/4-slot to snap into the 1/4 "wrench.

Figure 3 Adapter object diagram using the Wrench adapter example

Adapter Mode Commentary

We still use the logging program as an example to illustrate the adapter mode. Now there is a scenario where we want to use a third-party logging tool in software development that supports database logging DatabaseLog and text file records FileLog two ways that it provides to our API interface is the write () method, Here's how to use it:

Log.write ("Logging message!");

When the software system development in half, for some reason can not continue to use the logging tool, need to use another logging tool, it also supports database logging DatabaseLog and text file records FileLog two ways, Only the API interface it provides to us is the Writelog () method, using the following method:

Log.writelog ("Logging message!");

The class structure diagram for this logging tool is as follows:

Figure 4 Logging Tool class structure diagram

Its implementation code is as follows:

Public abstract class Logadaptee

{

public abstract void Writelog ();

}

public class Databaselog:logadaptee

{

public override void Writelog ()

{

Console.WriteLine ("Called Writelog Method");

}

}

public class Filelog:logadaptee

{

public override void Writelog ()

{

Console.WriteLine ("Called Writelog Method");

}

}

In our development of completed applications in the logging interface (may be called Ilogtarget interface, in this case, in order to more clearly illustrate, in the name of the adapter pattern of the relevant role name), but the use of a large number of write () method, the program has all passed the test, We cannot modify the interface. The code is as follows:

public interface Ilogtarget

{

void Write ();

}

At this point, perhaps we will think of modifying the current Logging Tool API interface, but because of copyright and other reasons we can not modify its source code, the adapter mode can come in handy. Let's use the adapter mode to make the logging tool conform to our current requirements.

As mentioned earlier, there are two implementations of the adapter pattern, first of all to see how the class adapter is implemented. The only way to do this now is to introduce a new type into the program, to inherit the Logadaptee class, and to implement the existing Ilogtarget interface. Since there are two types of logadaptee, naturally we will introduce two classes that are Databaselogadapter and Filelogadapter respectively.

Figure 5 Structure diagram after the class adapter is introduced

The implementation code is as follows:

public class Databaselogadapter:databaselog,ilogtarget

{

public void Write ()

{

Writelog ();

}

}

public class Filelogadapter:filelog,ilogtarget

{

public void Write ()

{

This. Writelog ();

}

}

One thing to note here is that we have written an adaptation class for each logging method, so why not write an adaptation class for abstract class Logadaptee? Because DatabaseLog and filelog inherit from the abstract class logadaptee at the same time, the implementation of their specific Writelog () method is different. The original behavior can be preserved only if it inherits from that specific class.

Let's take a look at this method of calling the client's program:

public class APP

{

public static void Main ()

{

Ilogtarget DbLog = new Databaselogadapter ();

Dblog.write ("Logging Database ...");

Ilogtarget FileLog = new Filelogadapter ();

Filelog.write ("Logging File ...");

}

}

Let's look at how the object adapter works to achieve our purpose. Object adapters are combined with objects rather than using inheritance, and the class structure diagram is as follows:

Figure 6 Structure diagram after introduction of the object adapter

The implementation code is as follows:

public class Logadapter:ilogtarget

{

Private Logadaptee _adaptee;

Public Logadapter (Logadaptee adaptee)

{

This._adaptee = Adaptee;

}

public void Write ()

{

_adaptee. Writelog ();

}

}

Compared to class adapters, you can see that the biggest difference is that the number of adapter classes is reduced, and you no longer need to create an adapter class for each specific logging method. At the same time, it can be seen that the adapter class is no longer dependent on the specific DatabaseLog class and the FileLog class when the object adapter is introduced, and it is better to implement loose coupling.

Let's look at the method of calling the client program:

public class APP

{

public static void Main ()

{

Ilogtarget DbLog = new Logadapter (new DatabaseLog ());

Dblog.write ("Logging Database ...");

Ilogtarget FileLog = new Logadapter (new FileLog ());

Filelog.write ("Logging Database ...");

}

}

Through the adapter mode, we have implemented the reuse of the existing components very well. Compared with the above two adaptation methods, it can be concluded that in the class adaptation mode, we get the adapter class Databaselogadapter and Filelogadapter has its inherited all the behavior of the parent class, but also has the interface ilogtarget all the behavior, This is in fact contrary to the object-oriented design principle of the single principle of responsibility, and the object adapter is more in line with the spirit of object-oriented, so in practical applications is not recommended in the way of the class adaptation. Let's take a different view of the class adaptation, assuming that we're going to fit the class to write to both the file and the database at the time of logging, then we'll write this with the object adapter:

public class Logadapter:ilogtarget

{

Private Logadaptee _adaptee1;

Private Logadaptee _adaptee2;

Public Logadapter (logadaptee adaptee1,logadaptee adaptee2)

{

This._adaptee1 = adaptee1;

This._adaptee2 = Adaptee2;

}

public void Write ()

{

_adaptee1. Writelog ();

_adaptee2. Writelog ();

}

}

If you use a class adapter instead, write this:

public class Databaselogadapter:databaselog,filelog,ilogtarget

{

public void Write ()

{

Writelog ();

}

}

Obviously wrong, such an explanation is a bit far-fetched, it is enough to explain some of the problems, of course, it is not said that the class adapter is not used in any case, for the development scenario, some time can still use the way the class adapter.

. NET the adapter mode in

1. One of the biggest applications of adapter mode in the. NET Framework is COM Interop. COM interop is like a link between COM and. NET, a bridge. We know that COM component objects are completely different from. NET class objects, but in order for COM clients to invoke. NET objects like COM components, make. NET programs

Like to use. NET objects, Microsoft uses the adapter mode to wrap COM objects in a way that is the RCW (Runtime callable Wrapper). The RCW is actually a. NET class generated by runtime that wraps the methods of COM components and internally implements calls to COM components. As shown in the following:

Figure 7. NET program and COM call each other

2.. NET is the application of another adapter pattern in the DataAdapter. Ado. NET provides multiple interfaces and base classes for unified data access, and one of the most important interfaces is idataadapter. The corresponding Dataadpter is an abstract class, which is the base class for data adapters between ADO and specific database operations. Dataadpter acts as a database-to-dataset bridge, which unifies the application's data operations to the dataset, regardless of the specific database type. You can even develop your own dataadpter for special data sources, which makes our applications compatible with these special data sources. Note This is a variant of the adapter.

Implementation Essentials

1. 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.

2. Adapter mode has two forms of object adapter and class adapter implementation structure, but the class adapter with "Multi-inheritance" implementation, resulting in poor high coupling, it is generally not recommended. Object adapters Use the "object combination" approach, more in line with the loose coupling spirit.

3. The implementation of the adapter pattern can be very flexible and does not have to adhere to the two structures defined in GOF23. For example, the "existing object" in adapter mode can be used as a new interface method parameter to achieve the purpose of adaptation.

4. The adapter model itself requires us to use the "interface-oriented programming" style as much as possible, so that it can be easily adapted at a later stage. [Cited above from MSDN Webcast]

Effect

For class adapters:

1. Match adaptee and Taget with a specific adapter class. The result is that when we want to match a class and all of its subclasses, class adapter will not be able to do the job.

2. Allows adapter to redefine part of the behavior of Adaptee, because adapter is a subclass of Adaptee.

3. Simply introduce an object that does not require an extra pointer to get adaptee indirectly.

For object adapters:

1. Allows a adapter to work concurrently with multiple adaptee, that is, adaptee itself, and all its subclasses (if there are subclasses). Adapter can also add functionality to all adaptee at once.

2. 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.

Applicability

Use the adapter mode in any of the following situations:

1. The system needs to use the existing classes, and the interfaces of this class do not meet the needs of the system.

2. You want to create a reusable class that works with some classes that are not too much related to each other, including some that might be introduced in the future. These source classes do not necessarily have very complex interfaces.

3. (for object adapters) in the design, you need to change the interfaces of several existing subclasses, and if you use the class's adapter pattern, you should make an adapter for each subclass, which is not practical.

Summarize

In short, through the use of adapter mode, you can fully enjoy the class library migration, class library reuse brings fun.

Resources

Shanhong, Java and patterns, electronic industry publishing house

James W. Cooper, C # Design model, electronic industry Press

Alan Shalloway James R. Trott, "Design Patterns explained", China Power Press

MSDN Webcast "C # Object-oriented design mode discussion on (7): Adapter Adapter mode (structured mode)"

NET design Pattern Part III Structural mode (7): Adapter mode (Adapter pattern)

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.