1. 程式人生 > >外觀模式(門面模式)

外觀模式(門面模式)

寫信的過程大家應該都還記得
——先寫信的內容,然後寫信封,再把信放到信封中,封好,投遞到信箱中進行郵遞,這個
過程還是比較簡單的,雖然簡單,但是這4個步驟都不可或缺!我們先把這個過程通過程式
實現出來,如圖

package FacadeP;

public interface ILetterProcess {
    //首先要寫信的內容
    public void writeContext(String context);
    //其次寫信封
    public void fillEnvelope(String address);
    //把信放到信封裡
    public void letterInotoEnvelope();
    //然後郵遞
    public void sendLetter();
}
package FacadeP;

public class LetterProcessImpl implements ILetterProcess {
    @Override
    public void writeContext(String context) {
        System.out.println("填寫信的內容..." + context);
    }

    @Override
    public void fillEnvelope(String address) {
        System.out.println("填寫收件人地址及姓名..." + address);
    }

    @Override
    public void letterInotoEnvelope() {
        System.out.println("把信放到信封中...");
    }

    @Override
    public void sendLetter() {
        System.out.println("郵遞信件...");
    }
}
package FacadeP;

public class Client {
    public static void main(String[] args) {
        ILetterProcess letterProcess = new LetterProcessImpl();
        letterProcess.writeContext("666");
        letterProcess.fillEnvelope("8888");
        letterProcess.letterInotoEnvelope();
        letterProcess.sendLetter();
    }
}

我們回過頭來看看這個過程,它與高內聚的要求相差甚遠,更不要說迪米特法則、介面
隔離原則了。你想想,你要知道這4個步驟,而且還要知道它們的順序,一旦出錯,信就不
可能郵寄出去,這在面向物件的程式設計中是極度地不適合,它根本就沒有完成一個類所具有的
單一職責。
還有,如果信件多了就非常麻煩,每封信都要這樣運轉一遍,非得累死,更別說要發個
廣告信了,那怎麼辦呢?還好,現在郵局開發了一個新業務,你只要把信件的必要資訊告訴
我,我給你發,我來完成這4個過程,只要把信件交給我就成了,其他就不要管了。非常好
的方案!我們來看類圖

package FacadeP;

public class ModenPostOffice {
    private ILetterProcess letterProcess = new LetterProcessImpl();
    public void sendLetter(String content,String address){
        letterProcess.writeContext(content);
        letterProcess.fillEnvelope(address);
        letterProcess.letterInotoEnvelope();
        letterProcess.sendLetter();
    }
}
package FacadeP;

public class Client1 {
    public static void main(String[] args) {
        ModenPostOffice modenPostOffice = new ModenPostOffice();

        String adderss = "oo";
        String context = "sss";

        modenPostOffice.sendLetter("context","address");
    }
}

執行結果是相同的。我們看看場景類是不是簡化了很多,只要與ModenPostOffice互動就
成了,其他的什麼都不用管,寫信封啦、寫地址啦……都不用關心,只要把需要的資訊提交
過去就成了,郵局保證會按照我們指定的地址把指定的內容傳送出去,這種方式不僅簡單,
而且擴充套件性還非常好,比如一個非常時期,寄往God Province(上帝省)的郵件都必須進行
安全檢查,那我們就很好處理了,如圖

 

 

package FacadeP;

public class Police {
    public void checkLetter(ILetterProcess letterProcess){
        System.out.println(letterProcess+" 信件已經檢查過了...");
    }
}