以画圆为例,如下
# -*- coding:utf-8 -*- __author__ = 'Ricky' class DrawingAPI1(object): """ 实现类1 """ def draw_circle(self, x, y, radius): print ('API1.cicle at {}:{} radius {}'.format(x, y, radius)) class DrawingAPI2(object): """ 实现类2 """ def draw_circle(self, x, y, radius): print ('API2.cicle at {}:{} radius {}'.format(x, y, radius)) class CicleShape(object): """ 抽象类 """ def __init__(self, x, y, radius, drawing_api): self._x = x self._y = y self._radius = radius self._drawing_api = drawing_api def draw(self): """ 对外提供公用接口 :return: """ self._drawing_api.draw_circle(self._x, self._y, self._radius) def scale(self, pct): """ 设置大小 :param pct: :return: """ self._radius *= pct if __name__ == '__main__': shapes = ( CicleShape(1, 2, 3, DrawingAPI1()), CicleShape(5, 7, 11, DrawingAPI2()), ) for shape in shapes: shape.scale(2.5) shape.draw() output: API1.cicle at 1:2 radius 7.5 API2.cicle at 5:7 radius 27.5