两种语言实现设计模式(C++和Java)(九:桥接模式)

当设计的class具有多个维度的属性,用单继承的方式进行设计会造成设计出的子类很多,分类困难。

桥接模式将抽象与实现分离,使它们可以独立变化。它是用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。

桥接模式的的特点:

1.扩展能力强,实现和继承分离。

2.其实现细节对客户透明。

考虑装操作系统,有多种配置的计算机,同样也有多款操作系统。如何运用桥接模式呢?可以将操作系统和计算机分别抽象出来,让它们各自发展,减少它们的耦合度。当然了,两者之间有标准的接口。这样设计,不论是对于计算机,还是操作系统都是非常有利的。

C++实现:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 //操作系统
 6 class OS
 7 {
 8 public:
 9     virtual void InstallOS_Imp() {}
10 };
11 class WindowOS: public OS
12 {
13 public:
14     void InstallOS_Imp() { cout<<"安装Window操作系统"<<endl; }
15 };
16 class LinuxOS: public OS
17 {
18 public:
19     void InstallOS_Imp() { cout<<"安装Linux操作系统"<<endl; }
20 };
21 class UnixOS: public OS
22 {
23 public:
24     void InstallOS_Imp() { cout<<"安装Unix操作系统"<<endl; }
25 };
26 //计算机
27 class Computer
28 {
29 public:
30     virtual void InstallOS(OS *os) {}
31 };
32 class DellComputer: public Computer
33 {
34 public:
35     void InstallOS(OS *os) { os->InstallOS_Imp(); }
36 };
37 class AppleComputer: public Computer
38 {
39 public:
40     void InstallOS(OS *os) { os->InstallOS_Imp(); }
41 };
42 class HPComputer: public Computer
43 {
44 public:
45     void InstallOS(OS *os) { os->InstallOS_Imp(); }
46 };
47 
48 int main()
49 {
50     cout << "Hello World!" << endl;
51     return 0;
52 }

Java实现:

扫描二维码关注公众号,回复: 6645529 查看本文章

猜你喜欢

转载自www.cnblogs.com/Asp1rant/p/10923744.html
今日推荐