桥接模式(BridgePattern)

定义

将俩个维度分离,使他们可以独立变化。又称为柄体(Handle and Body)模式或者接口(interface)模式。

结构图

image

 

角色与理解

  • 桥接模式包含如下角色:
    • Abstraction(抽象类):用于定义抽象类的接口,一般为抽象类而不是接口,其中维持一个Implementor的引用
    • RefinedAbstraction(扩充抽象类):继承或者实现抽象类,通常情况下为具体类而不是抽象类,实现抽象类中定义的抽象业务方法,在具体业务方法中可以调用Implementor中定义的业务方法
    • Implementor(实现类接口):定义实现类的接口,一般而言,Implementor接口仅提供基本操作,并交由子类去实现
    • ConcreteImplementor (具体实现类):实现Implementor中定义的基本操作方法
  • 抽象类持有实现类接口的对象,调用实现类接口中定义的方法
  • 本质上是两个独立变化的维度,一个抽象层引用另一个抽象层的东西,以实现通过实现类进行业务方法的调用

核心代码

抽象类

public abstract class Abstraction {
    protected Implementor implementor;
    //约束子类必须实现该构造函数
    public Abstraction(Implementor implementor) {
        this.implementor = implementor;
    }
    //自身的行为和属性
    public void operation() {
        this.implementor.operationImpl();
    }
}
public class RefinedAbstraction extends Abstraction {
    public RefinedAbstraction(Implementor implementor) {
        super(implementor);
    }
    @Override
    public void operation() {
        implementor.operationImpl();
    }
}
public interface Implementor {
    void operationImpl();
}
public class ConcreteImplementor implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("具体实现的操作!!!");
    }
}

客户端

public class Client {
    public static void main(String[] args) {
        Implementor imp = new ConcreteImplementor();
        Abstraction abs = new RefinedAbstraction(imp);
        abs.operation();;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值