设计模式-桥接模式

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

相关推荐
Asort30 分钟前
JavaScript设计模式(十六)——迭代器模式:优雅遍历数据的艺术
前端·javascript·设计模式
昨天的猫1 小时前
原来我们写的单例还存在缺陷~~
设计模式
Tiny_React1 小时前
智能体设计模式-CH13:人类参与环节(Human-in-the-Loop)
设计模式
Tiny_React1 小时前
智能体设计模式-CH09:学习与适应(Learning and Adaptation)
设计模式
Tiny_React1 小时前
智能体设计模式-CH10:模型上下文协议(Model Context Protocol)
设计模式
Tiny_React1 小时前
智能体设计模式-CH11:目标设定与监控(Goal Setting and Monitoring)
设计模式
Deschen12 小时前
设计模式-外观模式
java·设计模式·外观模式
恋红尘19 小时前
设计模式详解
设计模式
Code_Geo1 天前
agent设计模式:第一章节—提示链
microsoft·设计模式·agent·模型
懂得节能嘛.1 天前
【设计模式】Java规则树重构复杂业务逻辑
java·开发语言·设计模式