設計模式 - 包裝模式 (Structural Patterns - Facade Design Pattern)
前言
Wiki對於 Decorator Pattern的定義如下:
The Facade [1] design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
Facade Pattern應該是最常出現的Pattern之一,只要有基本物件觀念,基本上寫的許多Class都是Facade
- 將子物件包裝進主物件,簡化呼叫流程
- 讓呼叫端呼叫主物件
類別圖
範例
回到我們英雄遊戲活動,要與其他遊戲的英雄做聯名,這代表著我們需要呼叫許多外部系統,我們可以透過Facade Pattern將這些繁瑣的外部介面(or Api),包裝成我們統一的主介面
- 透過Facade包裝不同子系統的介面
class GameA {
public String getHero(String heroName) {
return "Game A hero";
}
}
class GameB {
public String getHero(String heroName) {
return "Game B hero";
}
}
class GameFacade {
public String getHero(String heroName, String gameType) {
if (gameType.equals("A")) {
return new GameA().getHero(heroName);
} else {
return new GameB().getHero(heroName);
}
}
}
public class Facade {
public static void main(String[] args) {
GameFacade gameFacade = new GameFacade();
System.out.println(gameFacade.getHero("Warrior", "A"));
}
}
結論
- 當呼叫太多Function/API時可以考慮使用Facade將細節都幫裝起來
留言
張貼留言