【发布时间】:2016-04-04 04:35:45
【问题描述】:
这是一个与设计模式相关的问题。我不是在寻找如何实现以下目标的答案,而是寻找最广泛接受的在服务中实现多态性的方法。
假设我有一个名为 getData 的服务。它需要获取一些数据,无论是来自数据库、文本文件还是硬编码的东西,并根据控制器中 $scope 上的设置进行输出。在下面的示例中,假设 getData 依赖于 dataSource。
angular.module('testApp').controller('testController'), [$scope, myAwesomeService, function ($scope, myAwesomeService){
$scope.dataSource = 'database'; //defines the source of the data
$scope.getData = function() {
//use myAwesomeService, get the data and output
if($scope.dataSource ==='database') {
return //do it the first way
}
else if($scope.dataSource ==='text') {
return //do it the second way
}
else if($scope.dataSource ==='csvfile') {
return //do it the third way
}
else if($scope.dataSource ==='form') {
return //do it the fourth way
}
}
}]);
问题:
您通常如何在 Javascript 中实现这一点?我不确定在 Javascript 中实现多态性的最佳实践。我习惯于使用接口并通过使用依赖注入并传入遵循相同接口的对象并从控制器调用通用方法来处理上述情况。通常,其他一些“类”会负责选择要实例化和传入的对象,因此控制器对“如何完成”的具体细节是不可知的。
如何在 AngularJS 中做到这一点? 该模式通常看起来如何?你能给出一个实现多态的“教科书”Angular 方法吗?
【问题讨论】:
标签: javascript angularjs oop polymorphism