Facade Pattern

Preface

Facade Pattern這個模式是用來為一個已經存在的介面定義一個新的介面,
這個新的介面可能有下列特性

  • 更高層
  • 更容易使用
  • 功能是本來系統的子集合

Compare

使用前

test.png

使用後

test.png

以上圖為例子,再最原始的情況下,每個Client連線進來後都必須要跟後方三個Manager進行溝通,這樣的話對於Client方面會很複雜,同時整個系統的密合度太高。

如果透過 Facade pattern 設計一個介面,把與內部的溝通都隱藏起來,然後外部的client只要與這個介面溝通即可,未來若是內部有任何變動,只要針對Facade的介面去修改,Client端不必去修改也能夠正常運作。

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

#original system

public class MapManager{
public Point getLocation(String name){....}
public Point setLocation(String name, Point point) {....}
...
}

public class ItemManager{
public ArrayList<Item> getItemList(String name) {....}
public void deleteItem(String name, Item item) {....}
public void addItem(String name, Item item) {....}
...
}

public class SkillManager{
public ArrayList<Skill> getSkill(String name) {....}
public void learnSkill(String name, String skillname) {...}
public void forgetSkill(String name, String skillname) {...}
...
}

#Facade interface

public class PersonManager{
private MapManger mapManager;
private ItemManager itemManager;
private SkillManager skillManager;

public PersonManager (){
mapManager = MapManager::GetSingleTon();
itemManager = ItemManager::GetSingleTon();
skillManager = SkillManager::GetSingleTon();
}
public loadData(String name,Point point,ArrayList<Item> itemList,ArrayList<Skill> skillList){
point = mapManager.getLocation(name);
itemList =ItemManager.getItemList(name);
skillList = skillManager.getSkill(name);

}
}

# Client

public class Client {
public Point point;
public ArrayList<Item> itemList;
public ArrayList<Skill> skillList;
public Client(String name){
PersonManager pm = new PersonManager();
PersonManager.loadData(name,point,itemList,skillList);
}
}