设计模式-桥接模式

桥接(Bridge)模式是一种结构型设计模式,主要目的是通过组合方式分离抽象接口和其实现部分。以下是一个简单的C#实现示例:

cs 复制代码
// 抽象部分
public abstract class Abstraction
{
    protected Implementor implementor;
 
    protected Abstraction(Implementor implementor)
    {
        this.implementor = implementor;
    }
 
    public virtual void Operation()
    {
        implementor.OperationImpl();
    }
}
 
// 修正抽象部分
public class RefinedAbstraction : Abstraction
{
    public RefinedAbstraction(Implementor implementor) : base(implementor)
    {
    }
 
    public override void Operation()
    {
        // 可以添加一些自己的操作
        base.Operation();
    }
}
 
// 实现部分接口
public interface Implementor
{
    void OperationImpl();
}
 
// 具体实现
public class ConcreteImplementorA : Implementor
{
    public void OperationImpl()
    {
        Console.WriteLine("ConcreteImplementorA Operation");
    }
}
 
public class ConcreteImplementorB : Implementor
{
    public void OperationImpl()
    {
        Console.WriteLine("ConcreteImplementorB Operation");
    }
}
 
// 客户端代码
public class Client
{
    public static void Main(string[] args)
    {
        Implementor implementorA = new ConcreteImplementorA();
        Abstraction abstractionA = new RefinedAbstraction(implementorA);
        abstractionA.Operation();
 
        Implementor implementorB = new ConcreteImplementorB();
        Abstraction abstractionB = new RefinedAbstraction(implementorB);
        abstractionB.Operation();
    }
}

在这个例子中,Implementor 接口定义了实现部分的行为,而 ConcreteImplementorAConcreteImplementorB 是具体的实现。Abstraction 类通过组合方式引用了 Implementor,并且可以在其中加入自己的操作。RefinedAbstraction 是对抽象部分的一些扩展。客户端代码中,我们可以通过更换实现部分来改变整个结构的行为。

相关推荐
山沐与山42 分钟前
【设计模式】Python责任链模式:从入门到实战
python·设计模式·责任链模式
繁星星繁1 小时前
【项目】基于SDK实现的智能聊天助手(使用api接入deepseek)------(二)
c++·设计模式·学习方法
职业码农NO.12 小时前
系统架构设计中的 15 个关键取舍
设计模式·架构·系统架构·ddd·架构师·设计规范·领域驱动
燕双嘤2 小时前
LLM:RAG,设计模式,Agent框架
人工智能·机器学习·设计模式
阿拉斯攀登2 小时前
设计模式:构建者模式
设计模式·建造者模式·构建者模式
山沐与山3 小时前
【设计模式】Python工厂模式与依赖注入:FastAPI的Depends到底在干嘛
python·设计模式·fastapi
.简.简.单.单.3 小时前
Design Patterns In Modern C++ 中文版翻译 第十一章 享元模式
c++·设计模式·享元模式
BD_Marathon4 小时前
设计模式——类图
设计模式
山沐与山4 小时前
【设计模式】 Python代理模式:从入门到实战
python·设计模式·代理模式
范纹杉想快点毕业5 小时前
C语言设计模式:从基础架构到高级并发系统(完整实现版)
c语言·开发语言·设计模式