设计模式-桥接模式

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

相关推荐
workflower32 分钟前
高质量数据集的类型
人工智能·机器学习·设计模式·自然语言处理·机器人
啦啦啦啦啦zzzz14 小时前
工具:动态类工厂和用配置文件存储属性
c++·设计模式·工具·动态工厂
Nontee19 小时前
设计模式:模板方法与策略,从“每个字都认识“到能说清它们在干嘛
java·数据库·设计模式
choumin21 小时前
行为型模式——模板方法模式
c++·设计模式·模板方法模式·行为型模式
啦啦啦啦啦zzzz1 天前
设计模式:建造者模式
c++·设计模式·建造者模式
梓仁沐白1 天前
【Agent 设计模式】推理技术
设计模式
Kinghiee1 天前
从使用场景切入前端常见设计模式
前端·设计模式
啦啦啦啦啦zzzz2 天前
设计模式:单例模式和工厂模式
c++·单例模式·设计模式·工厂模式
小白说大模型2 天前
Python 工程化设计模式:AI 项目中的异步流水线与策略模式实战
人工智能·python·设计模式
choumin2 天前
行为型模式——中介者模式
c++·设计模式·中介者模式·行为型模式