来自于《大话设计模式》
桥接模式(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 阅读(316)
评论(0) 编辑 收藏 引用