桥模式
当事物有两个维度,两个维度都有扩展
有些系统耦合度特别高,需要一定程度解耦合
举例耦合度高
#绘制图形 图形由颜色和形状组成
class shape(object):
pass
#图形
class circle(shape):
pass
class line(shape):
pass
class redcirle(object):
pass
class blackcricle(object):
pass
#.....
#颜色和图形耦合在一起,假如要加一个图形,比如长方形,
# 就要再写一堆各种颜色的长方形,这时候就要接耦合,使用桥模式
举例桥模式
#绘制图形 图形由颜色和形状组成
from abc import ABCMeta,abstractmethod
class shape(object):
#图形是抽象者
__metaclass__ = ABCMeta
@abstractmethod
#模拟画出一个图形
def draw(self):
pass
class color(object):
#颜色是实现者
__metaclass__ = ABCMeta
@abstractmethod
#模拟上色
def paint(self, shape):
pass
#细化抽象
class Circle(shape):
name = "圆形"
def __init__(self,color):
#使用组合
self.color = color
def draw(self):
self.color.paint(self)
#具体实现
class Red(color):
def paint(self, shape):
print "红色的%s" % shape.name
#client
c = Circle(Red())
c.draw()
桥模式扩展就没那么麻烦了,缺啥加啥,client需要什么自己组合
当然也可以颜色是抽象,图形是实现者
from abc import ABCMeta,abstractmethod
#抽象者
class color(object):
__metaclass__ = ABCMeta
@abstractmethod
def paint(self):
pass
#实现者
class shape(object):
__metaclass__ = ABCMeta
@abstractmethod
def draw(self, color):
pass
class red(color):
name = "红色"
def __init__(self, shape):
self.shape = shape
def paint(self):
self.shape.draw(self)
class circle(shape):
def draw(self, color):
print "%s的圆形" % color.name
#client
r = red(circle())
r.paint()