设计模式-桥接模式

桥接(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 是对抽象部分的一些扩展。客户端代码中,我们可以通过更换实现部分来改变整个结构的行为。

相关推荐
泯仲11 小时前
Ragent项目7种设计模式深度解析:从源码看设计模式落地实践
java·算法·设计模式·agent
WarrenMondeville13 小时前
1.Unity面向对象-单一职责原则
unity·设计模式·c#
bmseven13 小时前
23种设计模式 - 适配器模式(Adapter)
设计模式·适配器模式
bmseven14 小时前
23种设计模式 - 组合模式(Composite)
设计模式·组合模式
MarkHD15 小时前
RPA工程化实践:三种核心设计模式让复杂流程优雅可控
linux·设计模式·rpa
AI大法师16 小时前
字标Logo设计指南:中文品牌如何用字体做出高级感与辨识度
人工智能·设计模式
Yu_Lijing17 小时前
基于C++的《Head First设计模式》笔记——中介者模式
笔记·设计模式·中介者模式
程序员小寒17 小时前
JavaScript设计模式(四):发布-订阅模式实现与应用
开发语言·前端·javascript·设计模式
是糖糖啊19 小时前
Agent 不好用?先别怪模型,试试 Harness Engineering
人工智能·设计模式
jiankeljx19 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式