Problems to solve:
The adapter pattern transforms the interface of a class into another interface that the client expects, so that two classes that do not match the original interface can work together. For example, my HP notebook, American products, people in the United States voltage is 110V, and our Chinese voltage is 220V, to be able to use in China, you must find a transformer to turn the voltage before you can. This transformer is an adaptor.
Adapter mode has two modes of class adapter and object adapter, which we will discuss separately.
Class Adapters:
As can be seen from the diagram, the Adaptee class has no request method, and the customer expects this method. In order to enable customers to use the Adaptee class, provide an intermediate link, i.e. class adapter class, adapter class implements the target interface and inherits from Adaptee, The request method of the adapter class encapsulates the Adaptee Specificrequest method and achieves the goal of adaptation.
Because adapter and adaptee are inherited relationships, this determines that the adapter pattern is class.
The roles involved in this adapter pattern include:
Destination (target) Role: This is the interface that the customer expects. Because C # does not support multiple inheritance, target must be an interface, not a class.
Source (adaptee) role: A class that needs to fit.
Adapter (Adapter) Role: Converts the source interface to the target interface. This role must be a class
Simple implementation:
#include <iostream>
using namespace std;
"ITarget"
class Target
{public
:
//Methods
virtual void Request () {};
};
' Adaptee '
class adaptee
{public
:
//Methods
void Specificrequest ()
{
cout << "called Specificrequest ()" <<endl;
}
};
"Adapter"
class Adapter:public Adaptee, public Target
{public
:
//Implements ITarget interface
void Request ()
{
//possibly do some data manipulation
//And then call Specificrequest
this->specificrequest ();
}
};
int main ()
{
//Create adapter and place a request
Target *t = new Adapter ();
T->request ();
return 0;
}
Object adapters:
As you can see from the diagram: The client needs to invoke the request method, and Adaptee does not, and in order for the client to be able to use the Adaptee class, a wrapper (wrapper) class adapter is required. The wrapper class wraps a Adaptee instance to connect the client to the adaptee. Because adapter and adaptee are delegated, this determines that the adapter pattern is an object.