js設計模式 --- 外觀設計模式

外觀設計模式

外部與一個子系統的通訊必須經過一個統一的門面(Facade)對象進行,這就是門面模式。

外觀模式爲子系統提供了統一的界面, 屏蔽了子類的不一樣javascript

現代大型軟件發展到必定程度會很是複雜, 因而就須要對軟件進行模塊化開發, 將系統分紅各個模塊, 有利於維護和拓展,但即便這樣在咱們調用的時候依然要和許多類打交道, 依然很複雜, 因而外觀設計模式應運而生. 外觀設計模式就是爲多個子系統提供一個統一的外觀類來簡化外部人員操做, 下面是使用外觀模式先後的的醫院案例java

外觀模式就好像一個接待員免去了外部人員與各個科室進行交流, 應爲各個科室運做流程仍是比較複雜的, 經過一個熟悉業務的外觀類能夠大大提升醫院的效率.設計模式

  • 正常狀況
    圖片描述
  • 使用外觀模式後
    圖片描述

外觀模式設計兩種對象模塊化

  • 外觀類: 客戶端調用這個角色的方法。此角色知曉相關的子系統的功能和責任。正常狀況下,本角色會將全部從客戶端發來的請求委派到相應的子系統中去.
  • 子系統類:能夠同時有一個或者多個子系統。每一個子系統都不是一個單獨的類,而是一個類的集合。每個子系統均可以被客戶端直接調用,或者被門面角色直接調用。子系統並不知道門面的存在,對於子系統而言,門面僅僅是另外一個客戶端而已。
  • 外觀模式結構
    客戶端正常調用方式
    圖片描述

    外觀模式調用方式
    圖片描述this

實現

  • 未使用外觀模式spa

    • 子系統類prototype

      let Light = function () {  
      };
      Light.prototype.turnOn = function () {
        console.log('Light turn on');
      };
      Light.prototype.turnOff = function () {
        console.log('Light turn off');
      };
      
      let TV = function () { 
      };
      TV.prototype.turnOn = function () {
        console.log('TV turn on');
      };
      TV.prototype.turnOff = function () {
        console.log('TV turn off');
      };
      
      let Computer = function () {
      };
      Computer.prototype.turnOn = function () {
        console.log('Computer turn on');
      };
      Computer.prototype.turnOff = function () {
        console.log('Computer turn off');
      };
    • 客戶端調用設計

      let light = new Light();
      let tv = new TV();
      let computer = new Computer();
      
      light.turnOn();
      tv.turnOn();
      computer.turnOn();
      
      light.turnOff();
      tv.turnOff();
      computer.turnOff();
  • 使用外觀模式code

    • 子系統類模塊化開發

      //同上
    • 外觀類

      let Facade = function () {
        this.light = new Light();
        this.tv = new TV();
        this.computer = new Computer();
      }
      Facade.prototype.turnOn = function () {
        light.turnOn();
        tv.turnOn();
        computer.turnOn();
      }
      Facade.prototype.turnOff = function () {
        light.turnOff();
        tv.turnOff();
        computer.turnOff();
      }
    • 客戶端調用

      let facade = new Facade();
      
      facade.turnOn();
      facade.turnOff();
相關文章
相關標籤/搜索