实验9:桥接模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解桥接模式的动机,掌握该模式的结构;

2、能够利用桥接模式解决实际问题。

 

[实验任务一]:两个维度的桥接模式

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

#include <iostream>

 

using namespace std;

 

class Transportation

{

public:

    virtual void drive(){}

};

 

class Car:public Transportation

{

public:

    void drive()

    {

        cout<<"小轿车";

    }

};

 

class Bus:public Transportation

{

public:

    void drive()

    {

        cout<<"大巴";

    }

};

 

class Road

{

public:

    Transportation* transportation;

 

    Road(Transportation* transportation)

    {

        this->transportation=transportation;

    }

    virtual void driveOnRoad(){}

};

 

class CementRoad:public Road

{

public:

    CementRoad(Transportation* transportation):Road(transportation)

    {

 

    }

 

    void driveOnRoad()

    {

        transportation->drive();

        cout<<"行驶在水泥路"<<endl;

    }

};

 

class BituminousRoad:public Road

{

    public:

    BituminousRoad(Transportation* transportation):Road(transportation)

    {

 

    }

    void driveOnRoad()

    {

        transportation->drive();

        cout<<"行驶在柏油路"<<endl;

    }

};

 

 

int main()

{

    Transportation* transportation;

    Car car=Car();

    transportation=&car;

    CementRoad(transportation).driveOnRoad();

}

posted @ 2023-11-29 21:39  会秃头的小白  阅读(10)  评论(0编辑  收藏  举报