面向对象编程中,适配器模式和依赖注入有什么区别?

4

我在大学里学习软件架构和设计,目前正在学习设计模式。我发现适配器模式的实现看起来很像依赖注入,它被大多数框架所使用,比如Symfony、Angular、Vue、React,我们在构造函数中导入一个类并进行类型提示。

它们之间有什么区别,还是这些框架实现了适配器模式?


1
请详细解释您认为相似的内容。 - jaco0646
1个回答

7

依赖注入可以在适配器模式中使用。让我们一步一步地了解适配器模式和依赖注入是什么。

根据维基百科对 适配器模式 的描述:

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

让我们看一个现实生活中的例子。例如,我们有一个乘坐汽车旅行的旅行者。但有时他不能开车去某些地方。例如,在森林中他不能开车。但是他可以骑马去森林。然而,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);
}   

但是依赖注入是为一个对象提供其所需的对象(即其依赖项),而不是让它自己构造这些对象

因此,在我们的示例中,依赖关系是:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接