返回顶部

一缕半夏微光

温柔半两,从容一生

导航

软件设计⑨|桥接模式

 (1)C++

效果如下:

类图如下:

 

代码如下:

 1 #include <iostream>
 2 #ifndef __ROAD__H__
 3 #define __ROAD__H__
 4 using namespace std;
 5 
 6 class Road {
 7 public:
 8     virtual void run() = 0;
 9 };
10 
11 class UnpaveRoad : public Road {
12 public:
13     void run() override {
14         cout << "run on the speed way" << endl;
15     }
16 };
17 
18 class CementRoad : public Road {
19 public:
20     void run() override {
21         cout << "run on the street" << endl;
22     }
23 };
24 
25 class BusOnUnpaveRoad : public UnpaveRoad {
26 public:
27     void run() override {
28         cout << "Bus行驶在沥青路上" << endl;
29     }
30 };
31 
32 class CarOnUnpaveRoad : public UnpaveRoad {
33 public:
34     void run() override {
35         cout << "Car行驶在沥青路上" << endl;
36     }
37 };
38 
39 class BusOnCementRoad : public CementRoad {
40 public:
41     void run() override {
42         cout << "Bus行驶在水泥路上" << endl;
43     }
44 };
45 
46 class CarOnCementRoad : public CementRoad {
47 public:
48     void run() override {
49         cout << "Car行驶在水泥路上" << endl;
50     }
51 };
52 #endif
53 
54 int main() {
55     Road* busOnUnpaveRoad = new BusOnUnpaveRoad;
56     Road* carOnUnpaveRoad = new CarOnUnpaveRoad;
57     Road* busOnCementRoad = new BusOnCementRoad;
58     Road* carOnCementRoad = new CarOnCementRoad;
59 
60     busOnUnpaveRoad->run();
61     carOnUnpaveRoad->run();
62     busOnCementRoad->run();
63     carOnCementRoad->run();
64 
65     return 0;
66 }

参考链接:https://www.cnblogs.com/yuandonghua/p/11836249.html

posted on 2021-10-18 19:28  一缕半夏微光  阅读(35)  评论(0编辑  收藏  举报