我试图了解Bridge模式。来自Wiki的例子都可以。 但是如果我们有下一个设计呢?
如何实施不同的遥控器(例如红外线和Wi-Fi)?我应该使用Bridge模式以及如何操作?通过类比示例,我需要将所有方法与单个宽接口相结合,并使用硬件实现,如下图所示。但我认为这不是一个好主意。
答案 0 :(得分:1)
桥接模式很像适配器模式。
按照你的模型,我们假设你有一个RemoteControl
抽象类:
public abstract class RemoteControl
{
protected HadwareRemoteControl hardwareBridge;
//Can be injected using DI
public RemoteControl(HadwareRemoteControl hardwareBridge)
{
this.hardwareBridge= hardwareBridge;
}
public void on()
{
hardwareBridge.on();
}
public void off()
{
hardwareBridge.off();
}
}
该类的两个实现:
public class TVRemoteControl extends RemoteControl
{
public TVRemoteControl(TVHardwareRemoteControl hardwareBridge) {
super(hardwareBridge);
}
public void nextChannel() {
((TVHardwareRemoteControl)hardwareBridge).nextChannel();
}
public void previousChannel() {
((TVHardwareRemoteControl)hardwareBridge).previousChannel();
}
}
public class ModelRemoteControl extends RemoteControl
{
public ModelRemoteControl (ModelHardwareRemoteControl hardwareBridge) {
super(hardwareBridge);
}
public void moveForward() {
((ModelHardwareRemoteControl)hardwareBridge).moveForward();
}
public void moveBack() {
((ModelHardwareRemoteControl)hardwareBridge).moveBack();
}
}
现在,对于硬件桥,我们有一个基本接口:
public interface HadwareRemoteControl
{
public void on();
public void off();
}
还有两个接口:
public interface TVHadwareRemoteControl extends HardwareRemoteControl
{
public void nextChannel();
public void previousChannel();
}
public interface ModelHardwareRemoteControl extends HardwareRemoteControl
{
public void moveForward();
public void moveBack();
}
并且,正如你的设计,两个实现:
public class InfraredRemoteControl implements TVHardwareRemoteControl, ModelHardwareRemoteControl
{
public void on()
{
//Hardware Turn on
}
public void off()
{
//Hardware Turn off
}
public void nextChannel()
{
//Hardware Next channel
}
public void previousChannel()
{
//Hardware Previous channel
}
public void moveForward()
{
//Hardware Move Forward
}
public void moveBack()
{
//Hardware Move Back
}
}
public class WifiRemoteControl implements TVHardwareRemoteControl, ModelHardwareRemoteControl
{
public void on()
{
//Hardware Turn on
}
public void off()
{
//Hardware Turn off
}
public void nextChannel()
{
//Hardware Next channel
}
public void previousChannel()
{
//Hardware Previous channel
}
public void moveForward()
{
//Hardware Move Forward
}
public void moveBack()
{
//Hardware Move Back
}
}
从外部项目中,API的客户端可以更透明地使用硬件,甚至不了解这些实现:
TVRemoteControl tvRemote = Factory.CreateTVRemote();
//Depending on the injected hardware implementation, it may call InfraredRemoteControl or WifiRemoteControl
tvRemote.on();
tvRemote.nextChannel();