OOP 中的适配器模式与依赖注入有什么区别?
我一直在大学里学习软件架构和设计,并且在设计模式部分学习。我注意到适配器模式实现看起来类似于大多数框架使用的依赖注入,例如 Symfony、Angular、Vue、React,我们导入一个类并在构造函数中类型提示它。
它们有什么区别或者是适配器模式的框架实现?
I have been studying Software architectures and design in my uni and I am in the design pattern section. I noticed that the adapter pattern implementation looks similarl to the dependency injection that most framework uses such as Symfony, Angular, Vue, React, that we import a class and type hint it in our constructor.
What are their differences or is it the frameworks implementation of Adapter pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
依赖注入可以用在适配器模式中。那么让我们一步一步来。让我展示什么是适配器模式和依赖注入。
正如 Wiki 关于适配器模式所述:
让我们看一个现实生活中的例子。例如,我们有一个开车旅行的旅行者。
但有时有些地方他不能开车去。例如,他不能在森林里开车。但他可以在森林里骑马。但是,
Traveller
类没有办法使用Horse
类。所以,这是一个可以使用模式Adapter
的地方。让我们看看
Vehicle
和Tourist
类的样子:以及动物抽象及其实现:
这是从
Horse
到的适配器类Vehicle
:我们可以像这样运行我们的代码:
但是依赖注入是提供对象需要的对象(其依赖项)而不是让它自己构建它们。
所以我们例子中的依赖是:
注入是:
Dependency injection can be used in adapter pattern. So let's go step by step. Let me show what adapter pattern and dependency injection are.
As Wiki says about adapter pattern:
Let's see a real life example. For example, we have a traveller who travels by car.
But sometimes there are places where he cannot go by car. For example, he cannot go by car in forest. But he can go by horse in forest. However, class of
Traveller
does not have a way to useHorse
class. So, it is a place where patternAdapter
can be used.So let's look how
Vehicle
andTourist
class look like:and animal abstractions and its implementations:
This is an adapter class from
Horse
toVehicle
:We can run our code like this:
But dependency injection is providing the objects that an object needs (its dependencies) instead of having it construct them itself.
So dependency in our example is:
And injection is: