桥接模式

模式说明

桥接模式即将抽象部分与它的实现部分分离开来,使他们都可以独立变化。

桥接模式将继承关系转化成关联关系,它降低了类与类之间的耦合度,减少了系统中类的数量,也减少了代码量。

个人感觉,代理模式、适配器模式和桥接模式相类似,代理模式是一个代理对外表示一个特定的类,适配器模式相当于一个适配器代理多个类,而桥接模式则更加适用于多个对多个的时候

模式结构图

程序示例

说明:一个图形类,多个派生类;一个颜色类,多个派生类。派生类之间桥接。

代码:

 1 class Color(object):
 2     _name=''
 3     def __init__(self, name):
 4         self._name=name
 5 
 6 
 7 class Shape(object):
 8     _color=None
 9     _name=''
10     def __init__(self,name):
11         self._name=name
12     def setColor(self,color):
13         self._color=color
14     def draw(self):
15         print '%s  %s' % (self._name,self._color._name)
16         
17 #if __name__=='__main__':
18 #    color = Color('red')
19 #    shape = Shape('square')
20 #    shape.setColor(color)
21 #    shape.draw()
22 
23 class White(Color):
24     def __init__(self):
25         return super(White, self).__init__(self.__class__.__name__)
26 class Red(Color):
27     def __init__(self):
28         return super(Red, self).__init__(self.__class__.__name__)
29 
30 class Square(Shape):
31     def __init__(self):
32         return super(Square, self).__init__(self.__class__.__name__)
33 
34 class Circle(Shape):
35     def __init__(self):
36         return super(Circle, self).__init__(self.__class__.__name__)
37 
38 
39 if __name__=='__main__':
40     color = Red()
41     shape=Square()
42     shape.setColor(color)
43     shape.draw()
44 
45     color = White()
46     shape.setColor(color)
47     shape.draw()

运行结果:

参考来源:

http://www.cnblogs.com/chenssy/p/3679190.html

http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911.html

http://www.cnblogs.com/zhenyulu/articles/67016.html

原文地址:https://www.cnblogs.com/cotton/p/3931349.html