image

编辑人: 桃花下浅酌

calendar2025-06-12

message4

visits738

桥接模式 Bridge

分析&回答

桥接模式将抽象部分与它的实现部分分离,使它们都可以独立地变化。 它很好的支持了开闭原则和组合及复用原则。实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这些多角度分离出来让他们独立变化,减少他们之间的耦合。

2个相互耦合的系列,每个系列都有各自的产品变动。将这2个系列抽象成2个角色类,将各自的变化封装到对象的角色类中,然后再将2个角色类之间用组合的关系表示,这样就大大简化了使用类继承的复杂性,逻辑变得清晰了,易于扩展和维护。

桥接模式封装了变化,完成了解耦,实现了弱耦合

image-1691391863083

实例代码讲解:

/**
 * 抽象部分
 */
public class Abstraction{
    protected Implementor implementor;

    public void SetImplementor(Implementor implementor){
        this.implementor = implementor;
    }

    public virtual void Operation(){
        implementor.OperationImp();
    }
}

/**
 * 被提炼的抽象部分
 */
public class RefinedAbstraction:Abstraction{

    public override void Operation(){
        implementor.OperationImp();
    }
}

/**
 * 实现部分
 */
abstract public class Implementor{
    public abstract void OperationImp();
}

/**
 * 具体实现A
 */
public class conscreteImplementorA:Implementor{
    pulic override void OperationImp(){
        Console.Write("我是具体的A");
    }
}

/**
 * 具体实现B
  */    
public class conscreteImplementorB:Implementor{
    pulic override void OperationImp(){
        Console.Write("我是具体的B");
    }
}

/**
 * client端
 * @param args
 */
static void Main(string[] args)
{
    Abstraction ab = new RefinedAbstraction();
    ab.SetImplementor(new conscreteImplementorA());
    ab.Operaton();

    ab.SetImplementor(new conscreteImplementorB());
    ab.Operaton();

    Console.ReadLine();
}

反思&扩展


喵呜刷题:让学习像火箭一样快速,快来微信扫码,体验免费刷题服务,开启你的学习加速器!

创作类型:
原创

本文链接:桥接模式 Bridge

版权声明:本站点所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明文章出处。
分享文章
share