使用桥接模式不只改变你的实现,也改变你的抽象。
示例—遥控器
有很多遥控器,可以控制不同的电视。实现遥控器与电视之间的关系和配合过程。遥控器的设置频道方法最终由不同的电视实现类去实现。
UML图表示
桥接模式-遥控器代码演示
电视接口
package Bridge;
public interface TV {
void on();
void off();
void tuneChannel(int channel);
}
RCA电视类
package Bridge;
public class RCA implements TV {
@Override
public void on() {
System.out.println("RCA TV open");
}
@Override
public void off() {
System.out.println("RCA TV close");
}
@Override
public void tuneChannel(int channel) {
System.out.println("RCA TV is tuned to No." + channel + " Channel");
}
}
SONY电视类
package Bridge;
public class Sony implements TV {
@Override
public void on() {
System.out.println("Sony TV open");
}
@Override
public void off() {
System.out.println("Sony TV close");
}
@Override
public void tuneChannel(int channel) {
System.out.println("Sony TV is tuned to No." + channel + " Channel");
}
}
遥控器抽象类
package Bridge;
public abstract class RemoteControl {
TV implementor;
RemoteControl(TV implementor){
this.implementor = implementor;
}
void on(){
this.implementor.on();
}
void off(){
this.implementor.off();
}
void setChannel(int channel){
implementor.tuneChannel(channel);
}
}
RCA遥控器类
package Bridge;
public class RCAControl extends RemoteControl {
int currentStation = 0;
RCAControl(TV implementor) {
super(implementor);
}
void setStation(){
}
void nextChannel() {
setChannel(++currentStation);
}
void previousChannel() {
setChannel(currentStation - 1 < 0 ? 0 : --currentStation);
}
}
SONY遥控器类
package Bridge;
public class SonyControl extends RemoteControl {
int currentStation = 0;
SonyControl(TV implementor) {
super(implementor);
}
void setStation(){
}
void nextChannel() {
setChannel(currentStation + 1);
}
void previousChannel() {
setChannel(currentStation - 1 < 0 ? 0 : currentStation - 1);
}
}
测试代码
package Bridge;
public class ControlTVDriver {
public static void main(String[] args) {
RCAControl rcaControl = new RCAControl(new RCA());
SonyControl sonyControl = new SonyControl(new Sony());
rcaControl.on();
rcaControl.nextChannel();
rcaControl.nextChannel();
rcaControl.previousChannel();
rcaControl.off();
sonyControl.on();
sonyControl.nextChannel();
sonyControl.previousChannel();
sonyControl.previousChannel();
sonyControl.off();
}
}
测试结果
RCA TV open
RCA TV is tuned to No.1 Channel
RCA TV is tuned to No.2 Channel
RCA TV is tuned to No.1 Channel
RCA TV close
Sony TV open
Sony TV is tuned to No.1 Channel
Sony TV is tuned to No.0 Channel
Sony TV is tuned to No.0 Channel
Sony TV close
网友评论