依赖注入

Dependency Injection

依赖注入是一个在组件中给出的替代了硬的组件内的编码它们的依赖关系的软件设计模式。这减轻一个组成部分,从定位的依赖,依赖配置。这有助于使组件可重用,维护和测试。

其实就是模块与模块之间的解耦,依赖由别人管理,当我需要的时候,从依赖的那个人那里拿来就好了。

简单实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var inject = {
dependencies: {},
register: function (key, value) {
this.dependencies[key] = value;
},
resolve: function (func, scope) {
if (Array.isArray(func)) {
var last = func.length - 1;
var deps = func.slice(0, last);
func = func[last]
} else {
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var fnText = func.toString().replace(STRIP_COMMENTS, '');
var argDecl = fnText.match(FN_ARGS);
var deps = argDecl[1].split(/\s*,\s*/);
}

var arr = [];
for (var i = 0; i < deps.length; i++) {
if (this.dependencies.hasOwnProperty(deps[i])) {
arr.push(this.dependencies[deps[i]])
}
}
return function () {
func.apply(scope || {}, arr);
}
}
}

inject.register('$scope', {
'test': ''
});
inject.register('$http', {
'get': function () {
console.log('get');
}
});

MyController = inject.resolve([ '$scope', '$http', function ($scope, $http) {
$scope.test = 1;
$http.get('');
}]);
MyController();

MyController1 = inject.resolve(function ($scope, $http) {
$scope.test = 1;
$http.get('');
});
MyController1();

参考

http://www.alloyteam.com/2015/09/angularjs-study-of-dependency-injection/