适配器模式

#include <iostream>
#include <memory>

class Adaptee {
public:
    void concreteShow() { std::cout << "In Adaptee concreteShow()." << std::endl; }
};

class Target {
public:
    virtual void request () { std::cout << "In Target Show()." << std::endl; }
};

class Adapter1 : public Target {
public:
    Adapter1(std::shared_ptr<Adaptee> a) { this->a = a; }
    void request() override { a->concreteShow(); }
private:
    std::shared_ptr<Adaptee> a = nullptr;
};

class Adapter2 : public Target, public Adaptee {
public:
    void request() override { concreteShow(); }
};

int main(int argc, char *argv[]) {
    std::unique_ptr<Target> t = std::make_unique<Target>();
    t->request();
    std::shared_ptr<Adaptee> a = std::make_shared<Adaptee>();
    t = std::make_unique<Adapter1>(a);
    t->request();
    t = std::make_unique<Adapter2>();
    t->request();
    return 1;
}

  

posted @ 2022-02-25 17:48  南乡水  阅读(18)  评论(0编辑  收藏  举报