定义: 将抽象和实现解耦,使得两者可以独立变化
抽象化(Abstraction)角色:它的主要职责是定义出该角色的行为,同时保存一个对实例化角色的引用,该角色一般是抽象类
修正抽象化(RefinedAbstraction)角色:扩展抽象化角色,改变和修正父类对抽象化的定义。
实现化(Implementor)角色:这个角色给出实现化角色的接口,但不给出具体的实现。必须指出的是,这个接口不一定和抽象化角色的接口定义相同,实际上,这两个接口可以非常不一样。实现化角色应当只给出底层操作,而抽象化角色应当只给出基于底层操作的更高一层的操作。
具体实现化(ConcreteImplementor)角色:这个角色给出实现化角色接口的具体实现。
interface Implementor {
public void doSomething();
public void doAnything();
}
class ConcreteImplementor1 implements Implementor {
@Override
public void doSomething() {
System.out.println("ConcreteImplementor1 doSomething");
}
@Override
public void doAnything() {
System.out.println("ConcreteImplementor1 doAnything");
}
}
class ConcreteImplementor2 implements Implementor {
@Override
public void doSomething() {
System.out.println("ConcreteImplementor2 doSomething");
}
@Override
public void doAnything() {
System.out.println("ConcreteImplementor2 doAnything");
}
}
//将继承关系解耦,
//使原本的继承关系变为两个类Implementor/Abstraction,使之相互独立
abstract class Abstraction {
private Implementor implementor;
public Abstraction(Implementor implementor){
this.implementor = implementor;
}
public void request(){
implementor.doSomething();
}
public Implementor getImp(){
return this.implementor;
}
}
class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor implementor) {
super(implementor);
}
@Override
public void request() {
super.request();
super.getImp().doAnything();
}
}
public class Test {
public static void main(String[] args){
Implementor imp = new ConcreteImplementor1();
Abstraction abstraction = new RefinedAbstraction(imp);
abstraction.request();
}
}
优点
抽象和实现分离:桥接模式是为继承的缺点而设计的,使之可以不受继承的约束
扩展能力好
实现细节对客户透明
使用场景
不希望或不适用继承的场景
接口或抽象类不稳定的情况
重用性要求较高的场景
继承的情况下,父类的抽象方法子类必须实现。对子类的修改也会违反里氏替换原则。继承层次太深。都可以使用桥接模式