设计模式:桥接模式
简单点说,桥接模式就是一种具有两个层次的抽象。
2、JAVA实例代码
首先定义电视的接口
public interface ITV {public void on();public void off();public void switchChannel(int channel);}
?三星实现电视的接口
public class SamsungTV implements ITV {@Overridepublic void on() {System.out.println("Samsung is turned on.");} @Overridepublic void off() {System.out.println("Samsung is turned off.");} @Overridepublic void switchChannel(int channel) {System.out.println("Samsung: channel - " + channel);}}
?索尼实现电视接口
public class SonyTV implements ITV { @Overridepublic void on() {System.out.println("Sony is turned on.");} @Overridepublic void off() {System.out.println("Sony is turned off.");} @Overridepublic void switchChannel(int channel) {System.out.println("Sony: channel - " + channel);}}
?Remote control包含一个TV的引用
public abstract class AbstractRemoteControl {/** * @uml.property name="tv" * @uml.associationEnd */private ITV tv; public AbstractRemoteControl(ITV tv){this.tv = tv;} public void turnOn(){tv.on();} public void turnOff(){tv.off();} public void setChannel(int channel){tv.switchChannel(channel);}}
?定义一个具体的Remote Control的类
public class LogitechRemoteControl extends AbstractRemoteControl { public LogitechRemoteControl(ITV tv) {super(tv);} public void setChannelKeyboard(int channel){setChannel(channel);System.out.println("Logitech use keyword to set channel.");}}
?
public class Main {public static void main(String[] args){ITV tv = new SonyTV();LogitechRemoteControl lrc = new LogitechRemoteControl(tv);lrc.setChannelKeyboard(100);}}
?输出:
Sony: channel – 100Logitech use keyword to set channel.
?概括的说,桥接模式允许对实现有两层抽象,就像例子中的TV和Remote Control。因此这样更加灵活。