C#设计模式之:桥接模式

版权声明:每天要问下自己:“昨天的自己与今天的自己有啥区别?” https://blog.csdn.net/u010921682/article/details/82761165

桥接模式Bridge

将抽象部分与它的实现部分分离,使它们都可以独立地变化。

由于实现的方式有很多种,桥接模式的核心意图就是把这些实现独立出来,让它们各自地变化。
这就使得每种实现的变化不会影响其他实现,从而达到应对变化的目的。

UML

在这里插入图片描述

代码

abstract class Implementor
{
    public abstract void Operation();
}
class Abstraction
{
    protected Implementor implementor;

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

    public virtual void Operation()
    {
        implementor.Operation();
    }
}
class RefinedAbstraction : Abstraction
{
    public override void Operation()
    {
        implementor.Operation();
    }
}
class ConcreteImplementorA : Implementor
{
    public override void Operation()
    {
        Console.WriteLine("具体实现A的方法执行");
    }
}

class ConcreteImplementorB : Implementor
{
    public override void Operation()
    {
        Console.WriteLine("具体实现B的方法执行");
    }
}
// test
 Abstraction ab = new RefinedAbstraction();
 ab.SetImplementor(new ConcreteImplementorA());
 ab.Operation();

 ab.SetImplementor(new ConcreteImplementorB());
 ab.Operation();
// result
具体实现A的方法执行
具体实现B的方法执行

理解

实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合

合成/聚合复用原则

尽量使用合成/聚合,尽量不要使用类继承

聚合

表示一种弱的‘拥有’关系,体现的是A对象可以包含B对象,但B对象不是A对象的一部分

合成

表示一种强的‘拥有’关系,体现了严格的部分和整体的关系,部分和整体的生命周期一样

猜你喜欢

转载自blog.csdn.net/u010921682/article/details/82761165