Design Pattern-Structural-Bridge Pattern

Bridge mode

Overview

  • Separate the two dimensions of a thing so that it can change independently

Object

  • Abstraction
  • Refine Abstraction (RefindAbstraction)
  • Implementor
  • Concrete implementer (ConcreteImplementor)

Applicable scene

  • When things have performance in two dimensions, and it is possible to expand in each dimension

example

# 假设我们要进行不同颜色的形状绘制时,我们通常的  
# 做法是通过继承的方式分别对不同形状与颜色组合实  
# 现类的方式,例如红色矩形,红色矩形继承矩形,矩
# 形继承形状,桥模式将形状与颜色进行解耦,使用组
# 合方式在两个维度进行扩展

from abc import ABCMeta, abstractmethod

class Shape(metaclass=ABCMeta):
    def __init__(self, color):
        self.color = color
    
    @abstractmethod
    def draw(self):
        pass

class Color(metaclass=ABCMeta):

    @abstractmethod
    def paint(self, shape):
        pass

class Rectangle(Shape):
    name = "矩形"
    def draw(self):
        self.color.paint(self)

class Circular(Shape):
    name = "圆"
    def draw(self):
        self.color.paint(self)

class Red(Color):
    name = "红色"
    def paint(self, shape):
        print(f"{Red.name}的{shape.name}")

class Blue(Color):
    name = "蓝色"
    def paint(self, shape):
        print(f"{Blue.name}的{shape.name}")

rectangle = Rectangle(Red())
rectangle.draw()

advantage

  • Separation of abstraction and realization
  • Excellent scalability

Guess you like

Origin blog.csdn.net/DALAOS/article/details/113725671