设计模式-桥接模式
创始人
2024-11-17 17:38:17

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

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

相关内容

热门资讯

裸辞做“一人公司”,我后悔了 去年这个时候,一位以色列程序员正在东南亚旅行。他顺手把一个在脑子里转了很久的想法做成了产品,一个让任...
南京建成国内首个Pre-6G试... 4月21日,2026全球6G技术与产业生态大会在南京开幕。全息互动技术展台前,一名远在北京的工作人员...
超梵求职受邀参加“2025抖音... 超梵求职受邀参加“2025抖音巨量引擎成人教育行业生态大会”,探讨分享优质内容传播,服务万千学员。 ...
摩托罗拉Razr 2026(R... IT之家 4 月 22 日消息,摩托罗拉宣布新一代 Razr 折叠手机将于 4 月 29 日在美国发...
库克卸任,特纳斯领航:苹果新纪... 苹果首席执行官蒂姆·库克将卸任,硬件工程主管约翰·特纳斯将接任,苹果公司今天宣布此事。 库克将在夏季...