16. Adapter mode of "interface isolation mode"

1. Motivation

  • In a software system, due to changes in the application environment, it is often necessary to apply "some existing objects" in a new environment, but the interface of the new environment is not satisfied by these existing objects.
  • How to deal with this "change of migration"? How can we not only use the good implementation of existing objects, but also meet the interface required by the new application environment?

2. Adapters around us

 3. Schema definition

        Transforms the interface of a class into another interface that the client desires. The Adapter pattern enables classes that would otherwise not work together due to incompatible interfaces to work together.

                                                                                                                -----《Design Patterns》GOF

4. Structure

 Target in the above figure is the interface we want, and Adaptee is our historical interface

5. Code example

// 新接口
class ITarget{
public:
    virtual void Process() = 0;
};

// 老接口
class IAdaptee{
public:
    virtual void foo(int data) = 0;
    virtual int bar() = 0;
};

class OldClass : public IAdaptee{
    virtual void foo(int data){
        // ...
    }
    virtual int bar(){
        // ...
    }
};

// 由于某种内在某种功能可复用和关联性,可以将IAdaptee转成ITarget,如果毫无关联,是没有适配的意义的。
class Adapter : public ITarget{
protected:
    IAdaptee *pAdaptee;

public:
    Adapter(IAdaptee *pAdaptee){
        this->pAdaptee = pAdaptee;
    }

    virtual void Process(){
        // ...这个转换过程可能没有那么简单,会很复杂
        int res = pAdaptee->bar();
        pAdaptee->foo(res);
        // ...
    }
};

// 用一个旧的类,塞到Adapter里面,当做一个面向一个新接口来使用
void main(){
    IAdaptee *pAdaptee = new OldClass();
    ITarget *pTarget = new Adapter(pAdaptee);
    pTarget->Process();
}

6. Summary

  • The Adapter mode is mainly used for "the situation where you want to reuse some existing classes, but the interface is not consistent with the reuse environment", and is very useful in the aspects of legacy code reuse and class library migration.
  • GOF 23 defines two implementation structures of the Adapter pattern: object adapter and class adapter. However, the class adapter has used the "multiple inheritance" implementation method, which is generally not recommended. The object adapter adopts the method of "object composition", which is more in line with the spirit of loose coupling.
  • The Adapter mode can be implemented very flexibly, without having to stick to the two structures defined in Gof 23. For example, it is completely possible to use the "existing object" in the Adapter mode as a new interface method parameter to achieve the purpose of adaptation

Guess you like

Origin blog.csdn.net/bocai1215/article/details/127642935