设计模式-桥接模式

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

相关推荐
蔺太微16 小时前
桥接模式(Bridge Pattern)
设计模式·桥接模式
zhaokuner17 小时前
14-有界上下文-DDD领域驱动设计
java·开发语言·设计模式·架构
Geoking.20 小时前
【设计模式】抽象工厂模式(Abstract Factory)详解:一次创建“一整套产品”
设计模式·抽象工厂模式
zhaokuner21 小时前
12-深层模型与重构-DDD领域驱动设计
java·开发语言·设计模式·架构
不加糖4351 天前
设计模式 -- 适配器 & 策略模式
python·设计模式
__万波__1 天前
二十三种设计模式(十九)--备忘录模式
java·设计模式·备忘录模式
killer_queen48041 天前
设计模式-观察者模式
观察者模式·设计模式
Yu_Lijing1 天前
基于C++的《Head First设计模式》笔记——观察者模式
c++·笔记·设计模式
Geoking.1 天前
【设计模式】工厂方法模式(Factory Method)详解:从简单工厂到真正的“面向扩展”
设计模式·工厂方法模式