略懂略懂的IoC與DI
簡單來說,就是用來減少class間依賴的方法先來說說遇到的狀況,
實作遊戲時,
將UI在class終實體化
部分程式碼
...
void Start () {
GameControllOriginal o = new GameControllOriginal();
o.RunGame();
}
...
class 長這樣
class GameUI
{
public void GameUIInit() {
Debug.Log("UI Init!");
}
public void ShowSomething() {
Debug.Log("UI ShowSomething!");
}
public void UpdateUI() {
Debug.Log("UI UpdateUI!");
}
}
class GameControllOriginal
{
GameUIBase UI = null;
public GameControllOriginal() //我們在class new 出了 GameUI
{
GameUI ui = new GameUI();
UI = ui;
}
public void RunGame()
{
Debug.Log("HiHi!");
UI.ShowSomething();
UI.UpdateUI();
}
}
這時GameControllOriginal對GameUI 產生了依賴,當今天有新的GameUI2時勢必得修改GameControllOriginal,
因此,
我們使用DI解決這層問題!
依賴注入 DI(Dependency Injection)
在外面生成好class 再注入
部分程式碼
...
void Start () {
GameUI ui = new GameUI();
GameControllOriginal o = new GameControllOriginal(ui);
o.RunGame();
}
...
class 修改成這樣
class GameControllOriginal
{
GameUIBase UI = null;
public GameControllOriginal(GameUI ui) //相依性移出
{
UI = ui;
}
public void RunGame()
{
Debug.Log("HiHi!");
UI.ShowSomething();
UI.UpdateUI();
}
}
控制反轉 IOC(Inversion of Control)將依賴拔出來的這個過程,
就是控制反轉
假如今天的需求為:
希望將UI獨立出來,
即使沒有UI流程狀況下邏輯部分還是可以運作的
部分程式碼
...
void Start () {
bool NeedUI = false;
GameUI gameUI = null;
if (NeedUI)
gameUI = new GameUI();
else
gameUI = new GameUIBase();
GameControll controll = new GameControll(gameUI);
controll.RunGame();
}
...
class 長這樣
class GameUIBase
{
public GameUIBase() { }
public virtual void GameUIInit(){}
public virtual void ShowSomething(){}
public virtual void UpdateUI() {}
}
class GameUI : GameUIBase
{
public override void GameUIInit() {
Debug.Log("UI Init!");
}
public override void ShowSomething() {
Debug.Log("UI ShowSomething!");
}
public override void UpdateUI() {
Debug.Log("UI UpdateUI!");
}
}
class GameControll
{
GameUIBase UI =null;
public GameControll(GameUIBase ui)
{
UI = ui;
}
public void RunGame()
{
Debug.Log("HiHi!");
UI.ShowSomething();
UI.UpdateUI();
}
}
當不需要UI時輸出:HiHi!
當需要UI時輸出:
HiHi!
UI ShowSomething!
UI UpdateUI!
心得:
IoC與DI,
將變動大的部分都抽像化,
抽出class,
再依需求實作相對應的class並注入,
使開發更彈性~~
沒有留言:
張貼留言