外觀模式(Facade Pattern)隱藏系統(tǒng)的復(fù)雜性连茧,并向客戶端提供了一個(gè)客戶端可以訪問(wèn)系統(tǒng)的接口核蘸。這種類(lèi)型的設(shè)計(jì)模式屬于結(jié)構(gòu)型模式,它向現(xiàn)有的系統(tǒng)添加一個(gè)接口啸驯,來(lái)隱藏系統(tǒng)的復(fù)雜性客扎。
這種模式涉及到一個(gè)單一的類(lèi),該類(lèi)提供了客戶端請(qǐng)求的簡(jiǎn)化方法和對(duì)現(xiàn)有系統(tǒng)類(lèi)方法的委托調(diào)用罚斗。
關(guān)鍵代碼:在客戶端和復(fù)雜系統(tǒng)之間再加一層徙鱼,這一層將調(diào)用順序、依賴關(guān)系等處理好针姿。
優(yōu)點(diǎn): 1袱吆、減少系統(tǒng)相互依賴。 2距淫、提高靈活性绞绒。 3、提高了安全性榕暇。
缺點(diǎn):不符合開(kāi)閉原則蓬衡,如果要改東西很麻煩,繼承重寫(xiě)都不合適彤枢。
- 創(chuàng)建一個(gè)接口狰晚。
/**
* 1. 創(chuàng)建一個(gè)接口
* @author mazaiting
*/
public interface Shape {
/**
* 繪圖
*/
void draw();
}
- 創(chuàng)建實(shí)現(xiàn)接口的實(shí)體類(lèi)。
/**
* 2. 創(chuàng)建實(shí)現(xiàn)接口的實(shí)體類(lèi)缴啡。
* @author mazaiting
*/
public class Circle implements Shape{
public void draw() {
System.out.println("Circle::draw()");
}
}
/**
* 2. 創(chuàng)建實(shí)現(xiàn)接口的實(shí)體類(lèi)壁晒。
* @author mazaiting
*/
public class Rectangle implements Shape{
public void draw() {
System.out.println("Rectangle::draw()");
}
}
/**
* 2. 創(chuàng)建實(shí)現(xiàn)接口的實(shí)體類(lèi)。
* @author mazaiting
*/
public class Square implements Shape{
public void draw() {
System.out.println("Square::draw()");
}
}
- 創(chuàng)建一個(gè)外觀類(lèi)业栅。
/**
* 3. 創(chuàng)建一個(gè)外觀類(lèi)
* @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();
}
}
- 使用該外觀類(lèi)畫(huà)出各種類(lèi)型的形狀秒咐。
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()