• (十五)桥接模式


    桥接模式(Bridge),将抽象部分和它的实现部分分离,使他们都可以独立地变化。[DP]

    抽象和实现分离,并不是说,让抽象类与其派生类分离,因为这没有任何意义。
    实现,指的是抽象类和它的派生类用来实现自己的对象。

    在发现我们需要多角度去分类实现对象,而只用继承会造成大量的类增加,不能满足开放-封闭原则,就应该考虑用桥接模式了。

    #include <iostream>
    using namespace std;
    
    
    class Implementor
    {
    public:
        virtual void Operation() = 0;
    };
    
    class ConcreteImplementorA :public Implementor
    {
    public:
        void Operation()override{
            cout << "Concrete Implementor Operation A" << endl;
        }
    };
    
    class ConcreteImplementorB :public Implementor
    {
    public:
        void Operation()override{
            cout << "Concrete Implementor Operation B" << endl;
        }
    };
    
    class Abstraction
    {
    public:
        void SetImplementor(Implementor *impl){
            this->impl = impl;
        }
        virtual void Operation(){
            impl->Operation();
        }
    
    protected:
        Implementor *impl;
    };
    
    class RedfinedAbstraction :public Abstraction
    {
    public:
        void Operation()override{
            impl->Operation();
        }
    };
    
    
    int main()
    {
        Abstraction *abs = new RedfinedAbstraction();
    
        Implementor *impla = new ConcreteImplementorA();
        abs->SetImplementor(impla);
        abs->Operation();
    
        Implementor *implb = new ConcreteImplementorB();
        abs->SetImplementor(implb);
        abs->Operation();
    
        delete abs;
        delete impla;
        delete implb;
    
        return 0;
    }
    
  • 相关阅读:
    Redis面试题
    spring boot错误: 找不到或无法加载主类
    JAVA的高并发编程
    Redis多机多节点集群实验
    Redis单机多节点集群实验
    Redis集群概述
    Redis的持久化之AOF方式
    Redis的持久化之RDB方式
    Redis持久化介绍
    Redis Keys的通用操作
  • 原文地址:https://www.cnblogs.com/walkinginthesun/p/9618052.html
Copyright © 2020-2023  润新知