Dependency Injection Container in Swift

栏目: IT技术 · 发布时间: 4年前

内容简介:In this article I will talk about Dependency Injection Containers or DICs’ in swift. Im my previous article I talked aboutUsing DI helps decoupling a class, but does not fully solve the problem. What about the parent class who creates the child class? We j

How to loosely couple your whole project

Dependency Injection Container in Swift

Photo by Patrick Brinksma on Unsplash

In this article I will talk about Dependency Injection Containers or DICs’ in swift. Im my previous article I talked about how to decouple code in swift , and introduced four levels of the decoupling ladder, take a look if you are not sure what I mean. I have mentioned Dependency Injection or DI, as a method used to decouple classes from its’ dependencies, by injecting its dependencies from the outside world.

Using DI helps decoupling a class, but does not fully solve the problem. What about the parent class who creates the child class? We just move the coupling from the child class to the parent class. The parent class is now tightly coupled, lets look at an example

ParentClass creates both the serviceOne and serviceTwo . ServiceOne has a dependency to ServiceTwoProtocol and we can assume they are both loosely coupled or decoupled. ParentClass however is tightly coupled to ServiceOne and ServiceTwo , because it creates specific objects that can not be replaced. How then can we decouple ParentClass ?

One way is to inject ParentClass ’ dependencies, which in this case is serviceOne . Lets see how that would look like.

By injecting serviceOne we have made ParentClass loosely coupled! This is perfectly fine but lets think about this a bit deeper. We didn’t fully solve the issue, because now LooselyCoupledParentClass ’ parent will be tightly coupled. The class that creates the objects will always be tightly coupled to the created objects. We just passed on the problem to some other class. How then can we decouple as many classes as possible?

In a complex project there may be many classes, each one with its own dependencies. These classes will probably be ordered into a complex hierarchy. The creation of the objects will probably be scattered around, causing many classes to be tightly coupled.

In order to avoid this, we can create one object which is responsible for creating all other objects. You may have guessed it, I’m referring to the dependency injection container object, lets take a look at what it would look like.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

解密SEO

解密SEO

欧朝晖 / 电子工业出版社 / 2007-05-01 / 49.80元

《解密SEO:搜索引擎优化与网站成功战略》帮助读者建立搜索营销的概念,分析搜索营销中的几种形式的手段,并从认识搜索引擎的原理开始,导出搜索引擎优化的具体解释,向读者引入以搜索引擎优化为宗旨的网站建设的新观念和设计理念。对网站结构优化、单页优化、链接优化等技术进行了详细的解说和示范。读者还可以接触到网站养育的新概念,帮助读者网站发展成熟,达到网络营销的目标。对搜索引擎优化中观念上和技术上常犯的错误,......一起来看看 《解密SEO》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

SHA 加密
SHA 加密

SHA 加密工具