Design mode 13: Adapter mode (Adapter)

Source: Internet
Author: User

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:

    1. Target: Defines an interface that the client expects to be related to the problem domain
    2. Adapter: interface with Target interface. That overrides the interface in target.
    3. Adaptee: Defines an already existing interface that needs to be adapted.
    4. 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)

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.