这是一个与设计模式相关的问题。我不是在寻找如何实现以下目标的答案,而是在服务中实现多态性的最广泛接受的方法。
假设我有一个名为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中如何进行此操作图案通常会是什么样子?你能给出一个"教科书式"的实现多态性的角度方法吗?
我想发表评论,但我意识到它可能太长了,所以我要发布一个答案。
如果我们谈论的是CCD_ 1;继承可以通过原型设计来实现。
例如:
function Auto(name,year){
this.year=year;
this.name=name;
}
Auto.prototype.showYear = function(){
console.log(this.year);
}
function Car(name,year, model){
Auto.call(this,name,year);
this.model=model;
}
Car.prototype = Object.create(Auto.prototype);
//usage
var car = new Car('BMW',2015,'320d');
car.showYear(); // will output 2015
在ES6
中,这可以使用class
函数来完成。你可以在这里阅读更多关于这方面的信息(这将非常好:D)
下面你会发现一些代码可以回答你的问题。希望这就是你想要的:
function BaseService(){
this.dataSource='database';
}
BaseService.prototype.getData = function(){
console.log('base: get data');
}
function TextService(){
this.dataSource='text';
}
TextService.prototype = new BaseService();
TextService.prototype.getData = function(){
console.log('child text: get data');
}
function CsvService(){
this.dataSource='csv';
}
CsvService.prototype = new BaseService();
CsvService.prototype.getData = function(){
console.log('child csv: get data');
}
function FormService(){
this.dataSource='form';
}
FormService.prototype = new BaseService();
FormService.prototype.getData = function(){
console.log('child form: get data');
}
angular.module('myApp').factory('awesomeService', function(){
var service={};
service.getData = function(dataSource){
var sourceService;
if(dataSource='database'){
sourceService= new BaseService();
}
if(dataSource=='text'){
sourceService=new TextService();
}
if(dataSource=='csv'){
sourceService = new CsvService();
}
if(dataSource=='form'){
sourceService= new FormService();
}
return sourceService.getData(); // i'm going to assume getData returns a promise
}
return service;
});
angular.module('myApp').controller('myController', function($scope,awesomeService){
var myDataSource='database';
$scope.getData = function(){
awesomeService.getData(myDataSource).then(function(data){
$scope.result=data;
});
}
});