來自于《大話設計模式》
橋接模式(Bridge):將抽象部分與它的實現部分分離,使它們都可以獨立地變化。
結構型
UML 類圖:

代碼實現 C++:
1 #include <iostream>
2 using namespace std;
3
4 class HandsetSoft
5 {
6 public:
7 virtual void Run() = 0;
8 };
9
10 class HandsetGame : public HandsetSoft
11 {
12 public:
13 virtual void Run()
14 {
15 cout << "運行手機游戲!" << endl;
16 }
17 };
18
19 class HandsetAddressList : public HandsetSoft
20 {
21 public:
22 virtual void Run()
23 {
24 cout << "運行手機通訊錄!" << endl;
25 }
26 };
27
28 class HandsetBrand
29 {
30 protected:
31 HandsetSoft* hs;
32 public:
33 HandsetBrand() : hs(0) {}
34 virtual ~HandsetBrand()
35 {
36 delete hs;
37 }
38 void SetHandsetSoft(HandsetSoft* soft)
39 {
40 delete hs;
41 hs = soft;
42 }
43 virtual void Run() = 0;
44 };
45
46 class HandsetBrandN : public HandsetBrand
47 {
48 public:
49 virtual void Run()
50 {
51 hs->Run();
52 }
53 };
54
55 class HandsetBrandM : public HandsetBrand
56 {
57 public:
58 virtual void Run()
59 {
60 hs->Run();
61 }
62 };
63
64 int main()
65 {
66 HandsetBrand* ab = new HandsetBrandN;
67
68 ab->SetHandsetSoft(new HandsetGame);
69 ab->Run();
70
71 ab->SetHandsetSoft(new HandsetAddressList);
72 ab->Run();
73
74 delete ab;
75
76 ab = new HandsetBrandM;
77
78 ab->SetHandsetSoft(new HandsetGame);
79 ab->Run();
80
81 ab->SetHandsetSoft(new HandsetAddressList);
82 ab->Run();
83
84 delete ab;
85
86 return 0;
87 }
posted on 2011-04-29 20:42
unixfy 閱讀(319)
評論(0) 編輯 收藏 引用