2021.10.20 桥接模式c++
一、今日学习内容
[实验任务一]:两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
#include<iostream> #include<string> using namespace std; class Chexing { public: virtual void run()=0; }; class Bus:public Chexing{ public: void run(){ cout<<"公共汽车,"; } }; class Car:public Chexing { public: void run(){ cout<<"汽车,"; } }; class Road:public Chexing{ public: virtual void run()=0; }; class LiqingRoad:public Road{ private: Chexing *chexing; public: LiqingRoad(Chexing *chexing1) { chexing=chexing1; } void run() { chexing->run(); cout<<"在沥青路行驶"<<endl; } }; class ShuiniRoad:public Road{ private: Chexing *chexing; public: ShuiniRoad(Chexing *chexing1){ chexing=chexing1; } void run() { chexing->run(); cout<<"在水泥路行驶"<<endl; } }; int main() { Road *road1=new ShuiniRoad(new Car); Road *road2=new LiqingRoad(new Car); Road *road3=new ShuiniRoad(new Bus); Road *road4=new LiqingRoad(new Bus); road1->run(); road2->run(); road3->run(); road4->run(); }