桥接模式

#include <iostream>
#include <memory>

class Implementation {
public:
    virtual void show() = 0;
};

class ConcreteImplementation1 : public Implementation {
public:
    void show() override { std::cout << "In ConcreteImplementation1 show()." << std::endl; }
};

class ConcreteImplementation2 : public Implementation {
public:
    void show() override { std::cout << "In ConcreteImplementation2 show()." << std::endl; }
};

class Abstraction {
public:
    Abstraction(std::shared_ptr<Implementation> i) { this->i = i; }
    virtual void show() { i->show(); }
protected:
    std::shared_ptr<Implementation> i = nullptr;
};

class ExtendedAbstraction1 : public Abstraction {
public:
    ExtendedAbstraction1(std::shared_ptr<Implementation> i) : Abstraction(i) { }
    void show() override {
        std::cout << "In ExtendedAbstraction1 show()." << std::endl; 
        i->show();
    }
};

class ExtendedAbstraction2 : public Abstraction {
public:
    ExtendedAbstraction2(std::shared_ptr<Implementation> i) : Abstraction(i) { }
    void show() override {
        std::cout << "In ExtendedAbstraction2 show()." << std::endl; 
        i->show();
    }
};

int main(int argc, char *argv[]) {
    std::shared_ptr<Implementation> i1 = std::make_shared<ConcreteImplementation1>();
    std::shared_ptr<Implementation> i2 = std::make_shared<ConcreteImplementation2>();
    std::unique_ptr<Abstraction> a = std::make_unique<ExtendedAbstraction1>(i1);
    a->show();
    a = std::make_unique<ExtendedAbstraction2>(i2);
    a->show();
    return 1;
}

  

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