外觀模式(Facade),爲子系統中的一組接口提供一個一致的界面,定義一個高層接口,這個接口使得這一子系統更加容易使用。
結構
Facade:這個外觀類爲子系統提供一個共同的對外接口
Clients:客戶對象通過一個外觀接口讀寫子系統中各接口的數據資源。
適用場景
在以下情況下可以考慮使用外觀模式:
(1)設計初期階段,應該有意識的將不同層分離,層與層之間建立外觀模式。
(2) 開發階段,子系統越來越複雜,增加外觀模式提供一個簡單的調用接口。
(3) 維護一個大型遺留系統的時候,可能這個系統已經非常難以維護和擴展,但又包含非常重要的功能,爲其開發一個外觀類,以便新系統與其交互。
創建一個接口及實現該接口的實體類
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle::draw()");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Square::draw()");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle::draw()");
}
}
創建一個外觀類:
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;
public ShapeMaker() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}
public void drawCircle(){
circle.draw();
}
public void drawRectangle(){
rectangle.draw();
}
public void drawSquare(){
square.draw();
}
}
使用該外觀類畫出各種類型的形狀。
public class FacadePatternDemo {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
}
使用外觀模式的優點
(1)實現了子系統與客戶端之間的松耦合關係。
(2)客戶端屏蔽了子系統組件,減少了客戶端所需處理的對象數目,並使得子系統使用起來更加容易。