ivaneye.com

语言与模式-11桥接模式

意图

将抽象部分与它的实现部分分离,使它们都可以独立地变化。

适用性

Java实现

//电视机的接口
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);
    }
}
//遥控器要包含对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 SonyTV();
        LogitechRemoteControl lrc = new LogitechRemoteControl(tv);
        lrc.setChannelKeyboard(100);
    }
}

Clojure实现

first-class function轻松解决!

三星命名空间:

(ns samsung)
(defn on []
  (println "Samsung is turned on."))
(defn off []
  (println "Samsung is turned off."))
(defn switch-channel [channel]
  (println "Samsung: channel - " + channel))

索尼命名空间:

(ns sony)
(defn on []
  (println "Sony is turned on."))
(defn off []
  (println "Sony is turned off."))
(defn switch-channel [channel]
  (println "Sony: channel - " + channel))

RemoteController:

(ns remotecontroller)
(defn turn-on [f]
   (f))
(defn turn-off [f]
   (f))
(defn set-channel [f arg]
   (f arg))

直接调用:

(ns client
  (:require [sony :as tv]
            [remotecontroller :as c]))
(c/turn-on tv/on)
(c/set-channel tv/switch-channel 3)
(c/trun-off tv/off)

这么实现简直就是脱裤子放屁~~!

直接调用sony或samsung里的函数就行了!多此一举!