用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
实验要求:
1. 画出对应的类图;
2. 提交源代码;
1. #include <iostream>
2.
3. using namespace std;
4.
5. class Vehicle{
6. public:
7. virtual void drive(){}
8. };
9.
10. class Car:public Vehicle{
11. public:
12. void drive(){
13. cout<<"汽车行驶"<<endl;
14. }
15. };
16.
17. class Bus:public Vehicle{
18. public:
19. void drive(){
20. cout<<"公交车行驶"<<endl;
21. }
22. };
23.
24. class Road{
25. public:
26. Vehicle* vehicle;
27.
28. Road(Vehicle* vehicle){
29. this->vehicle=vehicle;
30. }
31. virtual void driveOnRoad(){}
32. };
33.
34. class CementRoad:public Road{
35. public:
36. CementRoad(Vehicle* vehicle):Road(vehicle){}
37.
38. void driveOnRoad(){
39. cout<<"水泥路";
40. vehicle->drive();
41. }
42. };
43.
44. class BituminousRoad:public Road{
45. public:
46. BituminousRoad(Vehicle* vehicle):Road(vehicle){}
47. void driveOnRoad(){
48. cout<<"沥青路";
49. vehicle->drive();
50. }
51. };
52.
53. int main(){
54. Vehicle* vehicle;
55. Car car=Car();
56. vehicle=&car;
57. CementRoad(vehicle).driveOnRoad();
58.
59. Bus bus=Bus();
60. vehicle=&bus;
61. BituminousRoad(vehicle).driveOnRoad();
62. }