Adapter mode:
An interface that transforms an interface of a class into another desired class. Adapters allow the interfaces to work with incompatible classes.
interfaceofclassintointerface clients expect. Adapter lets classes work together that couldn‘t otherwise because of incompatible interfaces.
Simply put, the adapter mode is to add an intermediate layer, remember that there is a phrase called software development in all problems can be solved by adding an intermediate layer.
The UML diagram is as follows:
Note that the relationship between adapter and Adaptee is just adapter need some of the features in Adaptee and must follow the interface of target. Adapter and Target are the relationship of inheritance level, and the relationship of Adaptee is related level.
Mainly include:
- Target: Defines an interface that the client expects to be related to the problem domain
- Adapter: interface with Target interface. That overrides the interface in target.
- Adaptee: Defines an already existing interface that needs to be adapted.
- Client: A class that works with the interface in target. It requires an interface in target and all cannot directly use the interface in Adaptee.
C + + code implementation is as follows;
#include <stdlib.h>#include <stdio.h>#include <iostream>classadaptee{ Public:voidSpecialrequest () {STD::cout<<"Call Specialrequest"<<STD:: Endl; }};classtarget{ Public:Virtual voidRequest () {STD::cout<<"Call request"<<STD:: Endl; }};classAdapter: Publictarget{ Public: Adapter () {} Adapter (Adaptee * a) { Adaptee=a; }voidRequest () {adaptee->specialrequest (); }Private: Adaptee * adaptee;};intMain () {Adaptee * ape=NewAdaptee (); Target * adapter=NewAdapter (APE); Adapter->request ();return 0;}
Execution output:
Design mode 13: Adapter mode (Adapter)