Reputation: 2119
One of the most clearest examples I read about services/factories/providers was that they corresponded to: A car, a factory that gives you cars(e.g. red car, blue car), and a configurable factory that outputs cars(e.g. high-quality cars, low-quality cars)
The part that is confusing me though is the "everything is a singleton" explanation. From the above example I had assumed that a "service" was a singleton that returned itself, and that the factory and provider were singletons that returned objects(each one unique). That is, if one controller got a blue car, and the other a red car, they would be two separate cars.
I think though the confusion comes from factories being written in two different ways. In one way, you return an object. This makes it functionally equivalent to a "service". In the other way, you return a function which is an instantiable object so that anything using this factory can get new separate instances.
Is this correct? Of the two methods of writing a factory is any one of them an anti-pattern?
Upvotes: 0
Views: 167
Reputation: 7531
From a blog I wrote specifically to answer this question:
So here it is. I’m going to summarize then follow up with some examples:
Why have multiple ways? Primarily because some systems that sit on JavaScript like TypeScript and CoffeeScript generate code that dictates one approach over the other, so it's there for flexibility.
To see full post with examples: http://csharperimage.jeremylikness.com/2014/01/understanding-providers-services-and.html
Upvotes: 1
Reputation: 6711
What I have seen relations to is a factory is the equivalent of the revealing module design pattern in Javascript.
Module Design Pattern - Singelton:
var x = (function() {
var y = 1,
zMethod = function() {
return y + y;
}
return {
y: y,
z: zMethod
}
}());
Angular Factory:
angular.module('app', [])
.factory('x', function() {
var y = 1,
zMethod = function() { return y + y; }
return {
y: y,
z: zMethod
}
});
Helps to clarify what is going on behind the scenes... But this is just one of the three parts!
Upvotes: 0