- 構造注入(Constructor Injection)
- 方法注入(Method Injection)
- 屬性注入(Property Injection)又稱為:Setter Injection
定義
Constructor Injection:指的是在類型的構造函數中,以傳參的形式,將該類型的依賴關系需求,以靜態的形式定義出來。
示例代碼
using System;
using UnityEngine;
public class ConstructorInjection : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
var description_0 = new Description_0();
var book_0 = new Book(description_0);//將 IDescription 依賴性需求,注入到Book中
book_0.Read();
var description_1 = new Description_1();
var book_1 = new Book(description_1);//將 IDescription 依賴性需求,注入到Book中
book_1.Read();
}
}
public class Book
{
private readonly IDescription m_description;
public Book(IDescription description)
{
if (description == null)
{
throw new ArgumentNullException("description");
}
m_description = description;
}
public void Read()
{
m_description.ToContent();
}
}
public interface IDescription
{
void ToContent();
}
public class Description_0 : IDescription
{
public void ToContent()
{
Debug.Log("內容_0");
}
}
public class Description_1 : IDescription
{
public void ToContent()
{
Debug.Log("內容_1");
}
}
補充:
- 由于構造注入中,構造函數中的參數就代表了類型對依賴需求的定義,而類型對依賴需求不應該有多重版本(重載),所以構造函數只應該有一種。
- 不應該在構造函數中添加其他業務邏輯(除了防御性語句的判空操作),也不要對依賴需求對象進行任何處理。
優缺點
優點 | 缺點 |
---|---|
簡單 | 對不支持構造傳參的運行方式支持不友好 |
可以明確的指出類型的依賴需求 | |
能夠保證依賴需求一定會注入 | |
直觀看出依賴需求的數量是否合理 |
使用優先級:高
定義
Method Injection:指的是通過方法參數的形式,向使用方提供需要的依賴對象。
示例代碼
using UnityEngine;
public class MethodInjection : MonoBehaviour
{
void Start()
{
var people = new People();
people.Eat(new Hamburger());
people.Eat(new Dumplings());
}
}
public class People
{
public void Eat(IFood food)
{
Debug.Log($"吃:{food.ToContent()}");
}
}
public interface IFood
{
string ToContent();
}
public class Hamburger : IFood
{
public string ToContent()
{
return "漢堡";
}
}
public class Dumplings : IFood
{
public string ToContent()
{
return "餃子";
}
}
補充:
- 每次依賴的使用者不同或每次調用方使用的依賴對象不同時,使用方法注入是個不錯的選擇。
- 不要對方法注入的依賴需求進行緩存操作。
優缺點
優點 | 缺點 |
---|---|
可以在每次方法操作時都提供不能的依賴需求 | 適用范圍有限 |
彌補構造注入中依賴需求爆炸的情況 | 依賴需求分散在不同方法中,不利于管理 |
使用優先級:中
定義
Property Injection:指的是通過對外公開的(pulic)屬性,將依賴對象的需求注入到使用方。
示例代碼
using UnityEngine;
public class PropertyInjection : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
var game = new Game();
game.Platform = new PC_Platform();
game.Play();
game.Platform = new Mobile_Platform();
game.Play();
}
}
public class Game
{
public IPlatform Platform { get; set; }
public void Play()
{
var tempStr = $"游戲運行在:{Platform.ToContent()} 平臺";
Debug.Log(tempStr);
}
}
public interface IPlatform
{
string ToContent();
}
public class PC_Platform : IPlatform
{
public string ToContent()
{
return "PC";
}
}
public class Mobile_Platform : IPlatform
{
public string ToContent()
{
return "Mobile";
}
}
補充:
- 只有在開發通用函數庫時,有默認的內置選項,并且該函數庫對依賴對象屬于非必要的前提下,才會使用屬性注入方式。
要是對依賴對象的需求范圍小且持續時間段,應該使用方法注入,剩下的情況使用構造注入。 - 當構造注入和方法注入都不能滿足需求時,再慎重使用屬性注入。
優缺點
優點 | 缺點 |
---|---|
操作簡單 | 適用范圍有限 |
理解成本提高 | |
會造成時序耦合 | |
只適用于通用組件(例:日志系統正式與開發環境的切換) |
使用優先級:低
總結:
從使用范圍和優缺點來看,使用的優先級由高到低依次為:構造注入--->方法注入--->屬性注入