设计模式——Adapter

中文名:适配器模式

作用

GOF中的描述:将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

描述的解释:两个不接口不同但功能相似的产品,转换为一种接口的形式。

优缺点

  1. 使其使用方式相似
  2. 改造的成本可能会很高,改造前需评估是否确实需要适配

结构

 适配分为两种,一种是类适配器,利用继承的技术;另一种是对象适配器,使用组合的技术。

Target类:目标接口

Adaptee类:带适配的类

Adapter类:将Adaptee类适配后的类

例子

结构中,Shape为Target类,TextView是待适配的类,TextShape是适配后的类。适配后调用方式与Shape类非常接近。

// StructureMode_Adapter.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>

struct Coord
{
    double x = 0;
};

struct Point
{
    double x = 0;
    double y = 0;

    Point(Coord _x, Coord _y)
    {
        x = _x.x;
        y = _y.x;
    }
};

class Manipulator {};

class Shape {
public:
    Shape() {}
    virtual void BoundingBox(Point& bottomLeft, Point& topRight)
    {

    }

    virtual Manipulator* CreateManipulator() const {
        return new Manipulator();
    }
};

class TextView {
public:
    TextView() {}
    void GetOrigin(Coord& x, Coord& y) const {

    }
    void GetExtent(Coord& width, Coord& height) const {

    }
    virtual bool IsEmpty() const {
        return false;
    }
};

// Adapter
class TextShape : public Shape, private TextView {
public:
    TextShape() {}
    virtual void BoundingBox(Point& bottomLeft, Point& topRight)
    {
        Coord bottom, left, width, height;
        
        GetOrigin(bottom, left);
        GetExtent(width, height);

        bottomLeft = Point(bottom, left);
        topRight = Point(bottom, left);
    }

    virtual bool IsEmpty() const {
        return TextView::IsEmpty();
    }

    virtual Manipulator* CreateManipulator() const {
        return new Manipulator();
    }

private:

};

int main()
{
    TextShape textShape;
}

Github链接:https://github.com/potterhere/CS-note/tree/master/DesignPattern/StructureMode_Adapter

相关模式

桥接模式

装饰器模式

参考资料

1. 《设计模式:可复用面向对象软件的基础》 GOF

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值