介绍
- 将抽象部分与它的实现部分分离,使它们都可以独立地变化。
UML图
- Client:桥接模式的调用者
- Abstraction抽象类(充当桥接的角色)Abstraction与Implementor是聚合关系。
Abstraction
package Bridge;
import interfaceAdapter.AbsAdpter;
public class Abstraction {
//聚合实现类
private Implementor implementor;
public Abstraction(Implementor implementor) {
super();
this.implementor = implementor;
}
protected void open(){
this.implementor.open();
}
protected void close(){
this.implementor.close();
}
protected void call(){
this.implementor.call();
}
}
Implementor
public interface Implementor {
void open();
void close();
void call();
}
ImplementorA
public class ImplementorA implements Implementor{
@Override
public void open() {
System.out.println("A打开了");
}
@Override
public void close() {
System.out.println("A关闭了");
}
@Override
public void call() {
System.out.println("A在打电话");
}
}
RefinedAbstractionA
public class RefinedAbstractionA extends Abstraction{
public RefinedAbstractionA(Implementor implementor) {
super(implementor);
}
public void call(){
super.call();
System.out.println("抽象类A");
}
public void close(){
super.close();
System.out.println("抽象类A");
}
public void open(){
super.open();
System.out.println("抽象类A");
}
}
Client
public class BridgeClient {
public static void main(String[] args) {
ImplementorA implementorA = new ImplementorA();
Abstraction abstraction = new RefinedAbstractionA(implementorA);
abstraction.call();
abstraction.close();
abstraction.open();
}
}