Java Facade Pattern(外觀模式)

外觀模式(Facade Pattern)隱藏系統(tǒng)的復(fù)雜性,并向客戶端提供了一個客戶端可以訪問系統(tǒng)的接口。這種類型的設(shè)計模式屬于結(jié)構(gòu)型模式,它向現(xiàn)有的系統(tǒng)添加一個接口,來隱藏系統(tǒng)的復(fù)雜性。
這種模式涉及到一個單一的類,該類提供了客戶端請求的簡化方法和對現(xiàn)有系統(tǒng)類方法的委托調(diào)用。

關(guān)鍵代碼:在客戶端和復(fù)雜系統(tǒng)之間再加一層,這一層將調(diào)用順序、依賴關(guān)系等處理好。

優(yōu)點: 1、減少系統(tǒng)相互依賴。 2、提高靈活性。 3、提高了安全性。
缺點:不符合開閉原則,如果要改東西很麻煩,繼承重寫都不合適。

  1. 創(chuàng)建一個接口。
/**
 * 1. 創(chuàng)建一個接口
 * @author mazaiting
 */
public interface Shape {
    
    /**
     * 繪圖
     */
    void draw();
}
  1. 創(chuàng)建實現(xiàn)接口的實體類。
/**
 * 2. 創(chuàng)建實現(xiàn)接口的實體類。
 * @author mazaiting
 */
public class Circle implements Shape{

    public void draw() {
        System.out.println("Circle::draw()");
    }

}

/**
 * 2. 創(chuàng)建實現(xiàn)接口的實體類。
 * @author mazaiting
 */
public class Rectangle implements Shape{

    public void draw() {
        System.out.println("Rectangle::draw()");
    }

}

/**
 * 2. 創(chuàng)建實現(xiàn)接口的實體類。
 * @author mazaiting
 */
public class Square implements Shape{

    public void draw() {
        System.out.println("Square::draw()");
    }

}
  1. 創(chuàng)建一個外觀類。
/**
 * 3. 創(chuàng)建一個外觀類
 * @author mazaiting
 */
public class ShapeMarker {
    private Shape circle;
    private Shape rectangle;
    private Shape square;
    
    public ShapeMarker(){
        circle = new Circle();
        rectangle = new Rectangle();
        square = new Square();
    }
    
    public void drawCircle() {
        circle.draw();
    }
    
    public void drawRectangle() {
        rectangle.draw();
    }
    
    public void drawSquare() {
        square.draw();
    }
    
}
  1. 使用該外觀類畫出各種類型的形狀。
public class Client {
    
    public static void main(String[] args) {
        
        ShapeMarker shapeMarker = new ShapeMarker();
        
        shapeMarker.drawCircle();
        shapeMarker.drawRectangle();
        shapeMarker.drawSquare();
        
    }

}
  1. 打印結(jié)果
Circle::draw()
Rectangle::draw()
Square::draw()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容