桥接模式

来源:互联网 发布:网络直播加速 编辑:程序博客网 时间:2024/05/17 06:47

简单来讲,桥接模式是一个两层的抽象。桥接模式是用于把抽象和实现脱耦,这样它们就能独立变化。 桥接模式使用了封装、聚合,可以用继承将不同的功能拆分为不同的类。

所谓的耦合,就是两个实体的某种强关联。而将它们的强关联去掉就是脱耦。强关联就是在编译期就已经确定的,无法在运行期动态改变的关联(Java继承是强关联,聚合是弱关联)。

示例代码:

首先定义电视机的接口ITV:

public interface ITV {    public void on();    public void off();    public void switchChannel(int channel);}

实现海尔的ITV接口:

public class HaierTV implements ITV {    @Override    public void on() {        System.out.println("Haier is turned on.");    }     @Override    public void off() {        System.out.println("Haier is turned off.");    }     @Override    public void switchChannel(int channel) {        System.out.println("Haier: channel - " + channel);    }}

再实现TCL的ITV接口:

public class TCLTV implements ITV {     @Override    public void on() {        System.out.println("TCL is turned on.");    }     @Override    public void off() {        System.out.println("TCL is turned off.");    }     @Override    public void switchChannel(int channel) {        System.out.println("TCL: channel - " + channel);    }}

遥控器要包含对TV的引用:

public abstract class AbstractRemoteControl {    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);    }}

定义遥控器的具体类:

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 TCLTV();        LogitechRemoteControl lrc = new LogitechRemoteControl(tv);        lrc.setChannelKeyboard(100);        }}

0 0
原创粉丝点击