桥接模式

用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。

 

 

 

//
// Created by 54417 on 2022-10-06.
//
#include <iostream>

using namespace std;
//抽象交通工具类,内部定义一个纯虚函数run
class Vehicle {
public:
    virtual void run() = 0;
};

class Car : public Vehicle {
public:
    void run() override {
        cout << "小轿车在跑" << endl;
    }
};

class Bus : public Vehicle {
public:
    void run() override {
        cout << "巴士在跑" << endl;
    }
};
//抽线路类,
class Road {
protected:
    Vehicle *vehicle1{};
public:
    virtual void runVehicle(Vehicle *vehicle) = 0;
};
//水泥路类
class Cement : public Road {
public:
    void runVehicle(Vehicle *vehicle) override {
        this->vehicle1=vehicle;
        cout<<"在泥泞路上----";
        vehicle1->run();
    }
};
//沥青类
class Asphalt :public Road{
public:
    void runVehicle(Vehicle *vehicle) override{
        this->vehicle1=vehicle;
        cout<<"在沥青路上----";
        vehicle1->run();
    }
};
int main() {
    Road *cement=new Cement();
    Road *asphalt=new Asphalt();
    Vehicle *car =new Car();
    Vehicle *bus=new Bus();
    cement->runVehicle(car);
    cement->runVehicle(bus);
    asphalt->runVehicle(car);
    asphalt->runVehicle(bus);
    return 0;
}

 

  

 

posted @ 2022-10-10 09:34  Blue啊  阅读(15)  评论(0编辑  收藏  举报