适配器模式(C++)

适配器:你什么样的需求,就给你提供什么样的服务

虚函数(Warning)
1.一个虚函数,在派生类层界面相同的重载函数都保持虚特性
2.虚函数必须是类的成员函数
3.不能将友元说明为虚函数,但虚函数可以是另一个类的友元
(因为一个类里声明友元时 由于友元不是自己的成员函数,所以参考 注意事项2 )
4.析构函数可以是虚函数,但构造函数不能是虚函数
如图(适配器模式)
这里写图片描述

简单的代码

#include<iostream>
using namespace std;

class Base//基类 接口
{
    public:
    virtual void work()
    {
        cout << "厨师" << endl;
    }
};

class master1:public Base
{
    public:
    void work()
    {
        cout << "川菜厨师" << endl;
    }
};

class master2:public Base
{
    public:
    void work()
    {
        cout << "粤菜厨师" << endl;
    }
};

class master3:public Base
{
    public:
    void work()
    {
        cout << "江苏菜厨师" << endl;
    }
};

int main(void)
{
    Base * base;
    master1 m1;
    master2 m2;
    master3 m3;
    base = &m1;
    base->work();
    base = &m2;
    base->work();
    base = &m3;
    base->work();
}
### C++ 中适配器设计模式的代码示例 适配器模式(Adapter Pattern)用于使两个不兼容接口能够一起工作。该模式通过创建一个新的类来作为两者之间的桥梁,从而允许原本由于接口不匹配而无法协同工作的对象可以共同协作。 下面是一个简单的例子,在这个例子中有一个现有的 `Target` 接口和一个已经存在的但是不符合 `Target` 所需接口的对象 `Adaptee`。为了使得 `Adaptee` 能够被当作 `Target` 使用,定义了一个新的 `Adapter` 类[^1]: ```cpp #include <iostream> using namespace std; // Target interface which client uses. class Target { public: virtual void request() const = 0; }; // Adaptee class with incompatible interface. class Adaptee { public: void specificRequest() const { cout << "Called Specific Request\n"; } }; // Adapter makes the Adaptee's interface compatible with the Target's. class Adapter : public Target { private: Adaptee* adaptee; public: Adapter(Adaptee* adpt) : adaptee(adpt) {} void request() const override { // Call Adaptee's method here to fulfill Target contract. adaptee->specificRequest(); } }; int main(){ Adaptee *adaptee = new Adaptee(); Target* target = new Adapter(adaptee); // Client calls methods on Target object without knowing it is actually an adapter. target->request(); delete adaptee; delete target; } ``` 在这个实现里,`Adapter` 继承自 `Target` 并持有指向 `Adaptee` 的指针成员变量。当调用者请求执行操作时,它实际上是在间接地让 `Adaptee` 完成相应的工作,但这一切对于客户端来说都是透明的[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值