ivaneye.com

语言与模式-06门面模式

意图

为子系统中的一组接口提供一个一致的界面,Facade模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

适用性

Java实现

public class Camara {
    public void turnOn(){
        System.out.println("开启摄像头!");
    }
    public void turnOff(){
        System.out.println("关闭摄像头!");
    }
}
public class Light {
    public void turnOn(){
        System.out.println("开灯!");
    }
    public void turnOff(){
        System.out.println("关灯!");
    }
}
public class Sensor {
    public void activate(){
        System.out.println("开启感应器!");
    }
    public void deactivate(){
        System.out.println("关闭感应器!");
    }
}
public class CamaraFacade {
    private Camara c1, c2;
    private Light l1, l2, l3;
    private Sensor s;
   {
        c1 = new Camara();
        c2 = new Camara();
        l1 = new Light();
        l2 = new Light();
        l3 = new Light();
        s = new Sensor();
    }
    public void activate(){
        c1.turnOn();
        c2.turnOn();
        l1.turnOn();
        l2.turnOn();
        l3.turnOn();
        s.activate();
    }
    public void deactivate(){
        c1.turnOff();
        c2.turnOff();
        l1.turnOff();
        l2.turnOff();
        l3.turnOff();
        s.deactivate();
    }
}
public class ClientTest {
    public static void main(String[] args) {
        CamaraFacade facade = new CamaraFacade();
        //打开
        facade.activate();
        //关闭
        facade.deactivate();
    }
}

Clojure实现

函数组合轻松搞定!

(defn turn-on-camara []
  (println "开启摄像头"))
(defn turn-on-light []
  (println "打开闪光灯"))
(defn turn-on-sensor []
  (println "开启感应器"))
(defn turn-on-facade []
  (turn-on-camara)
  (turn-on-light)
  (turn-on-sensor))