【发布时间】:2014-06-02 07:18:19
【问题描述】:
我试图了解服务和工厂之间的本质区别是什么(在 AngularJS 中)。说工厂是单例,服务每次调用都是新对象,对吗?
【问题讨论】:
-
没有。工厂是用于构造服务的函数。服务始终是单例的。见docs.angularjs.org/guide/services
标签: angularjs factory angularjs-service angular-services
我试图了解服务和工厂之间的本质区别是什么(在 AngularJS 中)。说工厂是单例,服务每次调用都是新对象,对吗?
【问题讨论】:
标签: angularjs factory angularjs-service angular-services
服务和工厂之间的唯一区别是服务是用 new 调用的
stuffToInject = new Service();
而工厂只是像函数一样被调用
stuffToInject = Factory();
否则一样,工厂和服务都是单例的。您需要问自己的唯一问题是我的服务是否需要新的操作员。如果没有,请使用module.factory,否则使用module.service。
示例:
function(){
this.foo=function(){
}
}
需要注册到 module.service
function(){
return {
foo:function(){}
};
}
可以注册到module.factory
【讨论】:
在 javascript 中,函数可以类似于具有实例变量、实例方法的类,并且可以新建:
// creating a class Box
function Box(col)
{
// instance member variable color, default to 'Red' if no color passed
var color = col || 'Red';
// instance method
this.getColor = function()
{
return color;
}
}
要实例化一个 Box,并用不同的颜色对其进行初始化:
var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue
var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green
Angular 服务用于注册构造函数,如 Box 示例。当服务被注入时,服务的一个实例被传递到你的函数中:
// declare a service
app.service('box', Box);
// inject instance of Box into controller: 'box' is a new Box()
app.controller('ctrl', function(box) {
alert(box.getColor()); // alerts 'Red'
});
相比之下,角度工厂不返回函数的实例。相反,它缓存并返回调用函数的结果:
// declare a factory
app.factory('user', function() {
// return an object literal
return {
name: 'john',
}
});
app.controller('ctrl', function(user) {
alert(user.name);// user is the object literal which was returned from the user factory.
};
将工厂视为返回函数结果的一种方式;结果是所有注入之间共享的单例。
将服务视为实例化类(或函数构造函数)的一种方式;该实例也是一个单例,并在所有注入之间共享。
工厂和服务都是单例的。
【讨论】:
a service follows a factory method design pattern (a new function instance is created with every injection).:不。服务和工厂都是单例。服务不会在每次注入时创建新实例。