def
将抽象和实现解耦, 使得两者可以独立地变化
usage
● 抽象和实现分离
这也是桥梁模式的主要特点, 它完全是为了解决继承的缺点而提出的设计模式。 在该模式下, 实现可以不受抽象的约束, 不用再绑定在一个固定的抽象层次上。
● 优秀的扩充能力
看看我们的例子, 想增加实现? 没问题! 想增加抽象, 也没有问题! 只要对外暴露的接口层允许这样的变化, 我们已经把变化的可能性减到最小。
● 实现细节对客户透明
客户不用关心细节的实现, 它已经由抽象层通过聚合关系完成了封装。
code
class DrawingAPI1(object):
def draw_circle(self, x, y, radius):
print('API1.circle at {}:{} radius {}'.format(x, y, radius))
# ConcreteImplementor 2/2
class DrawingAPI2(object):
def draw_circle(self, x, y, radius):
print('API2.circle at {}:{} radius {}'.format(x, y, radius))
# Refined Abstraction
class CircleShape(object):
def __init__(self, x, y, radius, drawing_api):
self._x = x
self._y = y
self._radius = radius
self._drawing_api = drawing_api
# low-level i.e. Implementation specific
def draw(self):
self._drawing_api.draw_circle(self._x, self._y, self._radius)
# high-level i.e. Abstraction specific
def scale(self, pct):
self._radius *= pct
def main():
shapes = (
CircleShape(1, 2, 3, DrawingAPI1()),
CircleShape(5, 7, 11, DrawingAPI2())
)
for shape in shapes:
shape.scale(2.5)
shape.draw()
if __name__ == '__main__':
main()
### OUTPUT ###
# API1.circle at 1:2 radius 7.5
# API2.circle at 5:7 radius 27.5