将抽象和实现分离开来,使其分别可以独立变化。
在一个抽象可能有多个实现时,通常使用继承来协调他们。
这样在扩展Window抽象的时候十分不方便,比如需要增加一个IconWindow抽象时,要增加两个新类:XIconWindow和PMIconWindow
而使用桥接模式可以通过搭配来实现不同功能:将加法变为乘法。
桥接模式的结构
桥接模式的优点
- 接口和实现的分离:一个实现未必不变地绑定在一个接口上。
- 提高可扩充性,可以独立的对Abstraction和Implementor层次进行扩充。
- 实现细节对客户透明。
代码:
public abstract class TV {
public abstract void on();
public abstract void off();
public abstract void turnChannel();
}
public class Sony extends TV{
@Override
public void on() {
System.out.println("sony.on()");
}
@Override
public void off() {
System.out.println("sony.off()");
}
@Override
public void turnChannel() {
System.out.println("sony.turnChannel()");
}
}
public class RCA extends TV {
@Override
public void on() {
System.out.println("RCA.on()");
}
@Override
public void off() {
System.out.println("RCA.off()");
}
@Override
public void turnChannel() {
System.out.println("RCA.turnChannel()");
}
}
public abstract class RemoteControl {
protected TV tv;
public RemoteControl(TV tv){
this.tv = tv;
}
public abstract void on();
public abstract void off();
public abstract void turnChannel();
}
public class ConcreteRemoteControl extends RemoteControl {
public ConcreteRemoteControl(TV tv) {
super(tv);
}
@Override
public void on() {
System.out.println("ConcreteRemoteControl.on()");
tv.on();
}
@Override
public void off() {
System.out.println("ConcreteRemoteControl.off()");
tv.off();
}
@Override
public void turnChannel() {
System.out.println("ConcreteRemoteControl.turnChannel()");
tv.turnChannel();
}
}
public class ConcreteRemoteControlplus extends RemoteControl {
public ConcreteRemoteControlplus(TV tv) {
super(tv);
}
@Override
public void on() {
System.out.println("ConcreteRemoteControl.on()");
tv.on();
}
@Override
public void off() {
System.out.println("ConcreteRemoteControl.off()");
tv.off();
}
@Override
public void turnChannel() {
System.out.println("ConcreteRemoteControl.turnChannel()");
tv.turnChannel();
}
public void turnOnThe4K(){
System.out.println("turnOnThe4K");
tv.on();
}
}
public class Client {
public static void main(String[] args) {
ConcreteRemoteControl control1 = new ConcreteRemoteControl(new Sony());
control1.on();
control1.off();
ConcreteRemoteControlplus control2 = new ConcreteRemoteControlplus(new RCA());
control2.turnOnThe4K();
control2.off();
}
}
运行结果:
ConcreteRemoteControl.on()
sony.on()
ConcreteRemoteControl.off()
sony.off()
turnOnThe4K
RCA.on()
ConcreteRemoteControl.off()
RCA.off()