外觀模式(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、提高了安全性。
缺點:不符合開閉原則,如果要改東西很麻煩,繼承重寫都不合適。
- 創(chuàng)建一個接口。
/**
* 1. 創(chuàng)建一個接口
* @author mazaiting
*/
public interface Shape {
/**
* 繪圖
*/
void draw();
}
- 創(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()");
}
}
- 創(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();
}
}
- 使用該外觀類畫出各種類型的形狀。
public class Client {
public static void main(String[] args) {
ShapeMarker shapeMarker = new ShapeMarker();
shapeMarker.drawCircle();
shapeMarker.drawRectangle();
shapeMarker.drawSquare();
}
}
- 打印結(jié)果
Circle::draw()
Rectangle::draw()
Square::draw()