java_bridge
来源:互联网 发布:数据采集仪数据存储 编辑:程序博客网 时间:2024/05/21 09:35
introduction:
桥接模式:
优点:
将实现予以解耦,让它和界面之间不再永久绑定。
抽象和实现可以独立扩展,不会影响对方。
对于“具体的抽象类”所做的改变,不会影响到客户。
当需要用不同的方式改变接口和实现时,适用于桥接模式
缺点:
增加了复杂度
demo:
description:桥接模式适用于多个层次之间的设计
TV.java
public interface TV { void on(); void off();}
Sony.java
public class Sony implements TV{ @Override public void on() { System.out.println("sony on"); } @Override public void off() { System.out.println("sony off"); }}
RCA.java
public class RCA implements TV{ @Override public void on() { System.out.println("RCA on"); } @Override public void off() { System.out.println("RCA off"); }}
RemoteControl.java
public abstract class RemoteControl { private TV tv; public RemoteControl(TV tv){ this.tv = tv; } public void off(){ tv.off(); } public void on(){ tv.on(); }}
public class RemoteControlImpl extends RemoteControl{ public RemoteControlImpl(TV tv){ super(tv); }}
Test.java
public class Test { public static void main(String[] args) { TV sony = new Sony(); TV rca = new RCA(); RemoteControl rc = new RemoteControlImpl(sony); rc.on(); rc.off(); rc = new RemoteControlImpl(rca); rc.on(); rc.off(); }}
抽象类中的方法都是以实现的方式实现的
具体子类是以抽象方式而不是实现方式实现的