gpt4 book ai didi

oop - OOP 中的适配器模式与依赖注入(inject)有什么区别?

转载 作者:行者123 更新时间:2023-12-05 01:52:53 26 4
gpt4 key购买 nike

我一直在我的大学学习软件架构和设计,我在设计模式部分。我注意到适配器模式实现看起来类似于大多数框架使用的依赖注入(inject),例如 Symfony、Angular、Vue、React,我们导入一个类并在我们的构造函数中类型提示它。

它们有什么区别或者是适配器模式的框架实现?

最佳答案

依赖注入(inject)可以用在适配器模式中。所以让我们一步一步来。让我来展示什么是适配器模式和依赖注入(inject)。

正如维基所说 adapter pattern :

In software engineering, the adapter pattern is a software designpattern (also known as wrapper, an alternative naming shared with thedecorator pattern) that allows the interface of an existing class tobe used as another interface. It is often used to make existingclasses work with others without modifying their source code.

让我们看一个真实的例子。例如,我们有一位乘汽车旅行的旅行者。但有时有些地方他不能开车去。例如,他不能在森林里开车。但是他可以在森林里骑马。但是,Traveller 类无法使用 Horse 类。因此,这是可以使用模式 Adapter 的地方。

那么让我们看看 VehicleTourist 类是怎样的:

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");
}
}

这是一个从 HorseVehicle 的适配器类:

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);
}

但是依赖注入(inject)是providing the objects that an object needs (its dependencies) instead of having it construct them itself .

所以我们例子中的依赖是:

public class Tourist
{
public void Travel(IVehicle vehicle) // dependency
{
vehicle.Drive();
}
}

注入(inject)是:

IVehicle horseVehicle = new HorseToVehicleAdapter(horse);
// now tourist travels in forest
tourist.Travel(horseVehicle); // injection

关于oop - OOP 中的适配器模式与依赖注入(inject)有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71411090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com