Clark To Do The blog of Clark

Java设计模式:桥接模式

注:本文为译文,原文出处java-design-patterns-in-stories

简单来讲, 桥接模式是一个两层的抽象.

桥接模式意为:”分离抽象与实现, 从而使抽象与实现可以独立的区分开来”. 桥接使用封装,聚合,利用继承在不同类中分离出职责.

1. 桥接模式的故事

电视与遥控器(图内与错别字)的例子展示了两层抽象. 包含一个电视的接口和一个遥控器的抽象类. 如你所知, 为电视与遥控器创建具体的类并不是一个好主意, 因为他们的厂商会制造不同的实现.

bridge design pattern

2. 桥接模式的Java代码

首先, 定义一个电视的接口: ITV

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

定义三星并实现ITV接口.

public class SamsungTV implements ITV {
    @Override
    public void on() {
        System.out.println("Samsung is turned on.");
    }

    @Override
    public void off() {
        System.out.println("Samsung is turned off.");
    }

    @Override
    public void switchChannel(int channel) {
        System.out.println("Samsung: channel - " + channel);
    }
}

定义索尼并实现ITV接口.

public class SonyTV implements ITV {

    @Override
    public void on() {
        System.out.println("Sony is turned on.");
    }

    @Override
    public void off() {
        System.out.println("Sony is turned off.");
    }

    @Override
    public void switchChannel(int channel) {
        System.out.println("Sony: channel - " + channel);
    }
}

遥控器持有电视的引用.

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);
    }
}

定一个具体的遥控器类.

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 - 100
Logitech use keyword to set channel.

总体来讲, 桥接模式允许两层抽象的实现, 在这种情况下, 电视和遥控器体现了这一点. 正因如此, 它来带来了更好的可扩展性.

3. Eclipse平台上的桥接模式

桥接模式在Eclipse的架构在有着举足轻重的地位.

参考:

  1. Gamma, E, Helm, R, Johnson, R, Vlissides, J: Design Patterns, page 151. Addison-Wesley, 1995
  2. Wiki Bridge Pattern
comments powered by Disqus