桥接模式又称桥梁模式,在软件系统中某些类型由于自身的逻辑,具有两个或多个维度的变化,如何应对这种多维度的变化?桥接模式使得软件系统能够轻松的沿着多个方向变化,而又不引入额外的复杂度。
桥接模式的用意是“将抽象化和实现化脱耦,使得二者可以独自的变化”。
以电灯开关为例:
所有电灯接口:
package com.demo.bridge.light;
public interface ILight {
public void turnOn();
public void keepLight();
public void turnOff();
}
开关基类:
package com.demo.bridge.baseswitch;
import com.demo.bridge.light.ILight;
public class BaseSwitch {
public ILight light;
public BaseSwitch(ILight light){
this.light = light;
}
public final void makeLight(){
this.light.turnOn();
this.light.keepLight();
this.light.turnOff();
}
}
普通电灯、和可变色电灯实现电灯接口:
package com.demo.bridge.light;
public class CommonLighe implements ILight {
@Override
public void turnOn() {
System.out.println("普通白织灯打开");
}
@Override
public void keepLight() {
System.out.println("普通白织灯亮开");
}
@Override
public void turnOff() {
System.out.println("普通白织灯关闭");
}
}
package com.demo.bridge.light;
public class ChangeableColorLight implements ILight {
@Override
public void turnOn() {
System.out.println("彩灯打开");
}
@Override
public void keepLight() {
System.out.println("彩灯亮着");
}
@Override
public void turnOff() {
System.out.println("彩灯关闭 ");
}
}
定义一个远程遥控开关,继承开发基类,控制灯色:
package com.demo.bridge.baseswitch;
import com.demo.bridge.light.ILight;
public class RemoteSwitch extends BaseSwitch {
public RemoteSwitch(ILight light) {
super(light);
}
public void remoteColorSwitch(int pa){
this.light.turnOn();
this.light.keepLight();
String color = "";
switch(pa){
case 1:
color = "暖色";
break;
case 2:
color = "蓝色";
break;
default:
color = "黄色";
break;
}
System.out.println("灯变成"+color);
this.light.turnOff();
}
}
测试:
package com.demo.bridge;
import com.demo.bridge.baseswitch.BaseSwitch;
import com.demo.bridge.baseswitch.RemoteSwitch;
import com.demo.bridge.light.ChangeableColorLight;
import com.demo.bridge.light.CommonLighe;
import com.demo.bridge.light.ILight;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
ILight common = new CommonLighe();
ILight changeableColorLight = new ChangeableColorLight();
System.out.println("-- 白炽灯 --");
BaseSwitch baseSwitch = new BaseSwitch(common);
baseSwitch.makeLight();
System.out.println("");
System.out.println("-- 彩灯 --");
RemoteSwitch remoteSwitch = new RemoteSwitch(changeableColorLight);
remoteSwitch.remoteColorSwitch(2);
}
}
控制台结果:
-- 白炽灯 --
普通白织灯打开
普通白织灯亮开
普通白织灯关闭
-- 彩灯 --
彩灯打开
彩灯亮着
灯变成蓝色
彩灯关闭