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

mik*_*ike 4 architecture oop frameworks design-patterns

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

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

Ste*_*pUp 7

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

正如 Wiki 关于适配器模式的描述:

在软件工程中,适配器模式是一种软件设计模式(也称为包装器,是与装饰器模式共享的替代命名),它允许将现有类的接口用作另一个接口。它通常用于使现有类与其他类一起工作,而无需修改其源代码。

让我们看一个现实生活中的例子。例如,我们有一个开车旅行的旅行者。但有时有些地方他不能开车去。例如,他不能在森林里开车。但他可以在森林里骑马。然而,class ofTraveller并没有办法使用Horseclass。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();
    }
}
Run Code Online (Sandbox Code Playgroud)

和动物抽象及其实现:

public interface IAnimal
{
    void Move();
}

public class Horse : IAnimal
{
    public void Move()
    {
        Console.WriteLine("Horse is going");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个从Horse到 的适配器类Vehicle

public class HorseToVehicleAdapter : IVehicle
{
    Horse _horse;
    public HorseToVehicleAdapter(Horse horse)
    {
        _horse = horse;
    }

    public void Drive()
    {
        _horse.Move();
    }
}
Run Code Online (Sandbox Code Playgroud)

我们可以像这样运行我们的代码:

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);
}   
Run Code Online (Sandbox Code Playgroud)

但是依赖注入是提供对象所需的对象(其依赖项),而不是让它自己构造它们

所以我们示例中的依赖关系是:

public class Tourist
{
    public void Travel(IVehicle vehicle) // dependency
    {
        vehicle.Drive();
    }
}
Run Code Online (Sandbox Code Playgroud)

注入是:

IVehicle horseVehicle = new HorseToVehicleAdapter(horse);
// now tourist travels in forest
tourist.Travel(horseVehicle); // injection
Run Code Online (Sandbox Code Playgroud)