我一直在研究軟體架構和設計,我在配接器模式實作部分。這種模式看起來類似于大多數框架使用的依賴注入,例如 Symfony、Angular、Vue、React 等。它們有什么區別?
還是配接器模式的框架實作?
uj5u.com熱心網友回復:
依賴注入可用于配接器模式。所以讓我們一步一步來。讓我展示一下配接器模式和依賴注入是什么。
正如維基所說的配接器模式:
在軟體工程中,配接器模式是一種軟體設計模式(也稱為包裝器,與裝飾器模式共享的替代命名),它允許將現有類的介面用作另一個介面。它通常用于使現有類在不修改其源代碼的情況下與其他類一起使用。
讓我們看一個現實生活中的例子。例如,我們有一個開車旅行的旅行者。但有時有些地方他不能開車去。例如,他不能在森林里開車。但他可以在森林里騎馬。但是,class ofTraveller沒有使用Horseclass 的方法。Adapter所以,它是一個可以使用模式的地方。
所以讓我們看看Vehicle類的Tourist樣子:
public interface IVehicle
{
void Drive();
}
public class Car : IVehicle
{
public void Drive()
{
Console.WriteLine("Tourist is going by car");
}
}
public class Tourist
{
public void Travel(IVehicle vehicle)
{
vehicle.Drive();
}
}
和動物抽象及其實作:
public interface IAnimal
{
void Move();
}
public class Horse : IAnimal
{
public void Move()
{
Console.WriteLine("Horse is going");
}
}
Horse這是一個從to的配接器類Vehicle:
public class HorseToVehicleAdapter : IVehicle
{
Horse _horse;
public HorseToVehicleAdapter(Horse horse)
{
_horse = horse;
}
public void Drive()
{
_horse.Move();
}
}
我們可以像這樣運行我們的代碼:
static void Main(string[] args)
{
Tourist tourist = new Tourist();
Car auto = new Car();
tourist.Travel(auto);
// tourist in forest. So he needs to ride by horse to travel further
Horse horse = new Horse();
// using adapter
IVehicle horseVehicle = new HorseToVehicleAdapter(horse);
// now tourist travels in forest
tourist.Travel(horseVehicle);
}
但是依賴注入是提供物件需要的物件(它的依賴項),而不是讓它自己構造它們。
所以我們例子中的依賴是:
public class Tourist
{
public void Travel(IVehicle vehicle) // dependency
{
vehicle.Drive();
}
}
注入是:
IVehicle horseVehicle = new HorseToVehicleAdapter(horse);
// now tourist travels in forest
tourist.Travel(horseVehicle); // injection
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/441591.html
上一篇:如何使用字串格式回圈并列印行號?
下一篇:創建由子類初始化的最終欄位
