1. 程式人生 > >什麼是建構函式注入(Constructor Injection)——一個具體的依賴注入例子

什麼是建構函式注入(Constructor Injection)——一個具體的依賴注入例子

Disclaimer: Almost all of this was "stolen" from the Ninject Wiki

什麼是建構函式注入呢,建構函式注入是不是就是一個具體的依賴注入呢,下面給個例子來解釋:

構造器注入就是一個具體的依賴注入的例子:

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.

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

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.

classSamurai{readonlySword sword;publicSamurai(){this.sword =newSword();}publicvoidAttack(string target){this.sword.Hit(target);}}

Now, we can create our Samurai and do battle!

classProgram{publicstaticvoidMain(){var warrior =newSamurai();
        warrior.Attack("the evildoers");}}

As you might imagine, this will print Chopped the evildoers clean in half

 to 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 be tightly coupled to 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{voidHit(string target);}

Then, our Sword class can implement this interface:

我們可以將Sword類定位一個介面

classSword:IWeapon{publicvoidHit(string target){Console.WriteLine("Chopped {0} clean in half", target);}}

And we can alter our Samurai class:

classSamurai{readonlyIWeapon weapon;publicSamurai(){this.weapon =newSword();}publicvoidAttack(string target){this.weapon.Hit(target);}}

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,我們在將其暴露出來成為一個建構函式的引數,這就是所謂的構建函式注入:

classSamurai{readonlyIWeapon weapon;publicSamurai(IWeapon weapon){this.weapon = weapon;}publicvoidAttack(string target){this.weapon.Hit(target);}}

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

classSamurai{IWeapon weapon;publicSamurai(){}publicvoidSetWeapon(IWeapon weapon){this.weapon = weapon;}publicvoidAttack(string target){this.weapon.Hit(target);}}

相關推薦

什麼是建構函式注入Constructor Injection——一個具體依賴注入例子

Disclaimer: Almost all of this was "stolen" from the Ninject Wiki 什麼是建構函式注入呢,建構函式注入是不是就是一個具體的依賴注入呢,下面給個例子來解釋: 構造器注入就是一個具體的依賴注入的例子: Le

spring依賴注入Depondency Injection

(1)lookup-method <bean id="engine" class="pojo.Engine"></bean> <bean id="car" abstrac

DVWA 黑客攻防實戰命令列注入Command Injection

文章會討論 DVWA 中低、中、高、不可能級別的命令列注入 這裡的需求是在伺服器上可以 ping 一下其他的伺服器 低階 如果你是從 初步認識網路漏洞這篇檔案過來的,可以跳過低階的。 這裡的需求是在伺服器上可以 ping 一下其他的伺服器 低階 低階程式碼是這樣。和之前的文章 內容是一樣

清晰架構Clean Architecture的Go微服務: 依賴注入Dependency Injection

在清晰架構(Clean Architecture)中,應用程式的每一層(用例,資料服務和域模型)僅依賴於其他層的介面而不是具體型別。 在執行時,程式容器¹負責建立具體型別並將它們注入到每個函式中,它使用的技術稱為依賴注入²。 以下是要求。 容器包的依賴關係: 容器包是唯一依賴於具體型別和許多外部庫的包,因為

Spring 學習十四——泛型依賴注入

•Spring 4.x 中可以為子類注入子類對應的泛型型別的成員變數的引用 整合多個配置檔案 •Spring 允許通過 <import> 將多個配置檔案引入到一個檔案中,進行配置檔案的整合。這樣在啟動 Spring 容器時,僅需要指定這個合併好的配置檔案就可以。 •im

編寫一個類Rectangle,有長itsLength,寬itsWidth等資料成員,有過載的建構函式Rectangle、Rectangleint width,int length

#include<iostream>using namespace std; class Rectangle{public:   Rectangle() {itsLength=10,itsWidth=5;}   Rectangle(int length ,int

7 More Effective C++—條款10建構函式內阻止記憶體洩漏

1 提出問題 上一篇文章中,我們討論瞭如下情況,當函式doSomething()被呼叫時,heap中資源無法被釋放,導致記憶體洩漏問題發生。 void function() { MyObject *object = new MyObject; object-

第四周預設建構函式 無參為1

/* *copyright(c) 2014,煙臺大學計算機學院 *All rights reserved。 *檔名稱:第四周(三角形) *作者:王忠 *完成日期:2015.4.1 *版本號:v1.0 * *問題描述:輸入三角形三條邊長,求出面積 周長 *輸入描述:輸入三角形

Spring建立物件的三種方法之一建構函式建立原始碼

Spring建立物件有三種方法,分別是: 1、建構函式建立 2、靜態工廠方法 3、例項工廠方法 這裡說下第一種方法,採用建構函式來建立,我這裡直接給原始碼,湊合著看看,能用就可以了,如果想要更深入的瞭解,那麼只有自己去找資料了。 第一個類:D1.java pa

C++繼承詳解之二——派生類成員函式詳解函式隱藏、建構函式與相容覆蓋規則

  在這一篇文章開始之前,我先解決一個問題。   在上一篇C++繼承詳解之一——初探繼承中,我提到了在派生類中可以定義一個與基類成員函式同名的函式,這樣派生類中的函式就會覆蓋掉基類的成員函式。   在譚浩強的C++程式設計這本書第十一章,351頁最下面有這麼

一個簡單的函式封裝JavaScript+html

本程式演示的是一個簡單的怎麼把程式碼寫的更好少點,提高程式碼的利用。 比如想給三個div不一樣的顏色,我們該怎麼寫?(本程式雖然很簡單,但是程式思想很好) 效果如下: 第一種寫法:<!D

黑馬程式設計師————面向物件概述,封裝,建構函式,this,static

概述:     面向物件(Object Oriented,OO)是當前計算機界關心的重點,它是90年代軟體開發方法的主流。面向物件的概念和應用已超越了程式設計和軟體開發,擴充套件到很寬的範圍。如資料庫系統、互動式介面、應用結構、應用平臺、分散式系統、網路管理結構、CAD技術

AngularJS模組與依賴注入函式依賴注入

1.模組與依賴注入angular.module('myApp', []);是初學時用到的,定義ng-app="myApp"這個應用,這就是一個模組。( )裡的內容分兩部分:    1. 前部分為name,要和ng-app的值保持一致;    2. 後面是一個字串陣列[ ],為

利用CSS注入無iFrames竊取CSRF令牌

來源:FreeBuf.COM 連結:http://www.freebuf.com/articles/web/162687.html(點選尾部閱讀原文前往) *參考來源:github,FB小編 secist 編譯 CSS僅僅只是一種用來表示樣式的語言嗎?當然不是!

beginthreadex()函式在建立多執行緒傳入回撥函式時,好像只能傳入全域性函式或類的靜態成員函式,請問能不能傳入類的成員函式非靜態

C++類成員函式直接作為執行緒回撥函式2009年06月01日 星期一 17:01我以前寫執行緒時要麼老老實實照著宣告寫,要麼使用C++類的靜態成員函式來作為回撥函式,經常會因為執行緒程式碼而破壞封裝.之前雖然知道類成員函式的展開形式,但從沒想過利用過它,昨天看深入ATL時無意中學

一些可能很常用的函式介紹持續更新

一些次常用的函式介紹: replace replace(初始位置,結束位置,替換字串); find (母字串).find(子字串,起始位置) 如果沒有設定起始位置預設為從頭開始。 random_shuffle() random_shuffle(起始位置,結束位置)

Spring學習第一章、第二節:依賴注入包括自動裝配,物件的注入

依賴注入 前言 Spring Bean 定義繼承 Bean 定義模板 正文 Spring依賴注入 基於構造器的依賴注入 基於Setter方法的依賴注入 自

第三章棧作業題2-棧及其應用-計算機17級 6-1 爆記憶體函式例項 6 分

6-1 爆記憶體函式例項 (6 分) 本題要求實現一個遞迴函式,使用者傳入非負整型引數n,使用者依次輸出1到n之間的整數。所謂遞迴函式就是指自己呼叫自己的函式。 說明: (1)遞迴函式求解問題的基本思想是把一個大規模問題的求解歸結為一個相對較小規模問題的求解, 小規模

模擬實現strcpy函式功能優化改進

strcpy函式,字串拷貝函式,傳入兩個引數,將第二個引數的值拷貝到第一個中去。 首先,給出一個普通的程式碼: #define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> void

Vue實戰指南之依賴注入provide / inject

案例 UI美眉說咱家的選項選單太醜了,小哥哥能不能美化一下呀,灑家自然是說小意思啦~ 自定義一個select元件,so easy~ 簡單粗暴型: <el-select v-model="favourite" :option="[]"></el-select> option作為資