桥接模式

1.概述

桥接模式(Bridge Pattern):将抽象部分与它的实现部分解耦,使得两者都能够独立变化。

又称,柄体(Handle and Body)模式或接口(Interface)模式。用抽象关联取代了传统的多层继承。

2.结构

(1)Abstraction(抽象类):定义抽象类接口,通常是抽象类而不是接口。定义并维护一个Implementor(实现类接口)类型的对象,关联关系。

(2)RefineAbstraction(扩充抽象类):扩充由Abstraction定义的接口,通常不再是抽象类而是具体类。

(3)Implementor(实现类接口):定义实现类接口,具体实现交给子类。

(4)ConcreteImplementor(具体实现类):继承、实现Implementor接口。

3.实现

namespace Bridge
{
    public interface Implementor
    {
        void OperationImpl();
    }
    public class ConcreteImplementor : Implementor
    {
        public void OperationImpl()
        {

        }
    }
    public abstract class Abstraction
    {
        protected Implementor implementor;
        public void SetImplementor(Implementor implementor)
        {
            this.implementor = implementor;
        }
        public abstract void Operation();
    }
    public class RefinedAbstraction : Abstraction
    {
        public override void Operation()
        {
            implementor.OperationImpl();
        }
    }
    public class Client
    {
        public void UseMethod()
        {
            Implementor implementor = new ConcreteImplementor();
            Abstraction abstraction = new RefinedAbstraction();
            abstraction.SetImplementor(implementor);
            abstraction.Operation();
        }
    }
}

桥接模式与适配器模式联用。

4.优缺点

(1)分离抽象接口及其实现部分。用对象之间的关联关系解耦了抽象和实现之间的固有绑定关系。

(2)很多情况下可以取代多层继承,减少子类数量。

(3)拓展方便,修改任意一个维度,不需修改原有系统。

(1)关联关系建立在抽象层,要求开发者一开始就针对抽象层进行设计与编程,增加系统理解与设计难度。

(2)正确识别出两个独立的维度,具有局限性,也需要一定经验。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值