惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
Stack Overflow Blog
Stack Overflow Blog
L
LangChain Blog
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
T
Tailwind CSS Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 【当耐特】
博客园 - 聂微东
V
Visual Studio Blog
博客园_首页
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Cloudflare Blog
人人都是产品经理
人人都是产品经理
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
F
Fortinet All Blogs
C
Check Point Blog
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - 隴上煙雨劍

什么是交叉验证 一句话设计模式 代理模式 中介模式 吐槽一下依赖倒置这个糟糕的名字 适配器模式 设计模式之状态模式 设计模式之装饰器模式 mysql插入数据如果存在则忽略 自己手写一个js的双向绑定 Java已经不再是以前的java了 无法访问9200端口的ElasticSearch服务 Forbidden You don't have permission to access / on this server [转帖]快速激活最新JetBrains公司系列产品包括最新的phpstorm10 【转】CI去掉index.php VirtualBox在win8.1中无法安装64位虚拟机 多谢Mono Ubuntu14.04上面安装mono3.12版本 更新线上数据库时候的安全操作
桥接模式
隴上煙雨劍 · 2023-07-22 · via 博客园 - 隴上煙雨劍

桥接模式说的是本来面向接口编程,但是呢,我们定义接口的时候吧,要考虑单一职责,所以不能眉毛胡子一把抓。

另外呢,在有些场景下,如果一个类的变化维度比较多(比如绘图中有颜色和形状这两个维度),那么使用继承会导致类爆炸,所以呢,搭个桥,组装一下

晕了吧,看看代码:

public interface Shape
{
    void Draw();
}


public interface Color
{
    void ApplyColor();
}


public class Circle : Shape
{
    private Color color;

    public Circle(Color color)
    {
        this.color = color;
    }

    public void Draw()
    {
        Console.Write("Drawing a Circle with ");
        color.ApplyColor();
    }
}

public class Rectangle : Shape
{
    private Color color;

    public Rectangle(Color color)
    {
        this.color = color;
    }

    public void Draw()
    {
        Console.Write("Drawing a Rectangle with ");
        color.ApplyColor();
    }
}


public class Red : Color
{
    public void ApplyColor()
    {
        Console.WriteLine("Red Color");
    }
}

public class Blue : Color
{
    public void ApplyColor()
    {
        Console.WriteLine("Blue Color");
    }
}


class Program
{
    static void Main(string[] args)
    {
        Shape circle = new Circle(new Red());
        circle.Draw();

        Shape rectangle = new Rectangle(new Blue());
        rectangle.Draw();
    }
}

通过使用桥接模式,我们可以在运行时决定图形和画笔的组合方式,而且它们可以独立地变化,不会相互影响。这样,桥接模式为我们提供了一种灵活的设计方式,使得系统的扩展更加容易。

 八股文如下:

桥接模式(Bridge Pattern)是一种结构型设计模式,它旨在将抽象部分与实现部分分离,从而使它们可以独立地变化。桥接模式使用了组合关系来实现这种分离,它将抽象部分和实现部分通过一个桥接接口连接起来,使它们可以独立地变化,互不影响。

桥接模式适用于以下情况:

  • 当一个类存在两个或多个独立变化的维度时,可以使用桥接模式将它们分离,使得每个维度可以独立变化。
  • 当一个类需要在多个维度上进行扩展,而使用继承会导致类爆炸时,可以使用桥接模式来避免类爆炸的问题。

桥接模式的关键是将抽象部分和实现部分分离,并通过桥接接口来连接它们。这样,抽象部分可以通过委托调用实现部分的方法来完成相应的功能,从而实现了两者的解耦。