栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

设计模式-桥模式

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设计模式-桥模式

桥模式

当事物有两个维度,两个维度都有扩展
有些系统耦合度特别高,需要一定程度解耦合
举例耦合度高

#绘制图形 图形由颜色和形状组成
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()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/739622.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号