什么是构造函数注入(Constructor Injection)——一个具体的依赖注入例子

前端之家收集整理的这篇文章主要介绍了什么是构造函数注入(Constructor Injection)——一个具体的依赖注入例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Disclaimer: Almost all of this was "stolen" fromthe Ninject Wiki

什么是构造函数注入呢,构造函数注入是不是就是一个具体的依赖注入呢,下面给个例子来解释:

构造器注入就是一个具体的依赖注入的例子:

@H_403_20@ Let’s examine the idea of dependency injection by walking through a simple example. Let’s say you’re writing the next blockbuster game,where noble warriors do battle for great glory. First,we’ll need a weapon suitable for arming our warriors.

class Sword { publicvoidHit(string target)Console.WriteLine("Chopped {0} clean in half",);}}

Then,let’s create a class to represent our warriors themselves. In order to attack its foes,the warrior will need an Attack() method. When this method is called,it should use its Sword to strike its opponent.

Samuraireadonly sword;Samurai()this.sword =newSword();Attacksword(target Now,we can create our Samurai and do battle!

ProgramstaticMainvar warrior  warrior"the evildoers" As you might imagine,this will printChopped the evildoers clean in halfto the console. This works just fine,but what if we wanted to arm our Samurai with another weapon? Since the Sword is created inside the Samurai class’s constructor,we have to modify the implementation of the class in order to make this change.

When a class is dependent on a concrete dependency,it is said to betightly coupledto that class. In this example,the Samurai class is tightly coupled to the Sword class. When classes are tightly coupled,they cannot be interchanged without altering their implementation. In order to avoid tightly coupling classes,we can use interfaces to provide a level of indirection. Let’s create an interface to represent a weapon in our game.

interfaceIWeapon 我们可以将Sword类定位一个接口

: And we can alter our Samurai class:

 weaponweapon weapon Now our Samurai can be armed with different weapons. But wait! The Sword is still created inside the constructor of Samurai. Since we still need to alter the implementation of Samurai in order to give our warrior another weapon,Samurai is still tightly coupled to Sword.

Fortunately,there is an easy solution. Rather than creating the Sword from within the constructor of Samurai,we can expose it as a parameter of the constructor instead.Also known as Constructor Injection.

幸运的是,有一个容易解决方法,不是在Samurai构造函数内创建Sword,我们在将其暴露出来成为一个构造函数的参数,这就是所谓的构建函数注入:

( As Giorgio pointed out,there's also property injection(属性注入). That would be something like:

SetWeapon}
原文链接:https://www.f2er.com/javaschema/283454.html

猜你在找的设计模式相关文章