解决的问题
开发一个电视机遥控器app,要求可以适配各种的电视机品牌(Sony、Samsung等)。遥控器分为基础版和高级版,基础版只能开关机,高级版可以切换频道。
可以这样设计:
这样设计很好,有很好的拓展性,将来可以支持拓展更多的电视机品牌(XiaoMi、Huawei等),也可以支持拓展更多遥控器版本(例如,电影版,VIP版等)。
但是随着拓展越来越多,创建的类也会越来越多。这种情况,可以考虑使用Bridge Pattern(桥接模式)优化代码:
其实上面两种方式都可以,但是用桥接模式,代码会精简得多。
代码
Device
:
package com.cong.designpattern.bridge;
public interface Device {
public void trunOn();
public void trunOff();
public void setChannel(Number channel);
}
SonyDevice
:
package com.cong.designpattern.bridge;
public class SonyDevice implements Device{
@Override
public void trunOn() {
System.out.println("Trun on");
}
@Override
public void trunOff() {
System.out.println("Trun off");
}
@Override
public void setChannel(Number channel) {
System.out.println("Set channel to " + channel);
}
}
RemoteControl
:
package com.cong.designpattern.bridge;
public class RemoteControl {
protected Device device;
public RemoteControl(Device device) {
this.device = device;
}
public void trunOn() {
device.trunOn();
}
public void trunOff() {
device.trunOff();
}
}
AdvancedRemoteControl
:
package com.cong.designpattern.bridge;
public class AdvancedRemoteControl extends RemoteControl {
public AdvancedRemoteControl(Device device) {
super(device);
}
public void setChannel(Number channel) {
device.setChannel(channel);
}
}
Test code:
SonyDevice sonyDevice = new SonyDevice();
RemoteControl sonyRemoteControl = new RemoteControl(sonyDevice);
sonyRemoteControl.trunOn();
sonyRemoteControl.trunOff();
AdvancedRemoteControl sonyAdvancedRemoteControl = new AdvancedRemoteControl(sonyDevice);
sonyAdvancedRemoteControl.setChannel(1);