OOP 中的适配器模式与依赖注入有什么区别?

What is the difference between Adapter pattern vs dependency injection in OOP?

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

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

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

正如维基所说 adapter pattern

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

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

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

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 的适配器 class:

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

但是依赖注入是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();
    }
}

注入是:

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