简单来讲,桥接模式是一个两层的抽象。
桥接模式是用于“把抽象和实现分开,这样它们就能独立变化”。 桥接模式使用了封装、聚合,可以用继承将不同的功能拆分为不同的类。
1、桥接模式的故事
电视和遥控器(图中有错字)是一个完美展示两层抽象的例子。你有一个电视机的接口,还有一个遥控器的抽象类。我们都知道,将它们中任何一个定义为一个具体类都不是好办法,因为其它厂家会有不同的实现方法。
2、桥接模式Java示例代码
首先定义电视机的接口:ITV
4 | public void switchChannel( int channel); |
实现三星的 ITV 接口。
1 | public class SamsungTV implements ITV { |
4 | System.out.println( "Samsung is turned on." ); |
9 | System.out.println( "Samsung is turned off." ); |
13 | public void switchChannel( int channel) { |
14 | System.out.println( "Samsung: channel - " + channel); |
再实现索尼的ITV接口。
1 | public class SonyTV implements ITV { |
5 | System.out.println( "Sony is turned on." ); |
10 | System.out.println( "Sony is turned off." ); |
14 | public void switchChannel( int channel) { |
15 | System.out.println( "Sony: channel - " + channel); |
遥控器要包含对TV的引用。
1 | public abstract class AbstractRemoteControl { |
3 | * @uml.property name="tv" |
8 | public AbstractRemoteControl(ITV tv){ |
16 | public void turnOff(){ |
20 | public void setChannel( int channel){ |
21 | tv.switchChannel(channel); |
定义遥控器的具体类。
1 | public class LogitechRemoteControl extends AbstractRemoteControl { |
3 | public LogitechRemoteControl(ITV tv) { |
7 | public void setChannelKeyboard( int channel){ |
9 | System.out.println( "Logitech use keyword to set channel." ); |
2 | public static void main(String[] args){ |
4 | LogitechRemoteControl lrc = new LogitechRemoteControl(tv); |
5 | lrc.setChannelKeyboard( 100 ); |
输出如下:
2 | Logitech use keyword to set channel. |
总结一下, 桥接模式允许两层实现的抽象,上面的电视机和遥控器就是很好的例子。可见,桥接模式提供了更多的灵活性。
3、Eclipse 平台上的桥接模式
在Eclipse 架构使用的模式中,桥接模式占有重要的地位。