While reading about factories in this article, I came across these two terms AbstractFactory and ConcreteFactory.
While reading on StackOverflow, I found some good answers (like this SO question) that talk about factories and abstract factories, but still not clear about what a concrete factory is.
So, I wanted to ask:
- What is a concrete factory?
- How is it different from an abstract factory?
EDIT: Asking the question #2 in a separate question (will update link here soon).
My understanding so far (about factories):
- At high level, I understand that, by a factory we refer to a method that returns a brand new something (can be anything, an object, a method, anything that's needed as our requirement), that we'd call a factory. Here, please correct me if I'm wrong.
- that factories encapsulate and separate object creation from the rest of your code. Below is an example to illustrate the same:
// This function is a factory. When called, creates and returns a new object every time
function ourFactoryFn (firstName, lastName) {
var a = {
prop1: firstName,
prop2: lastName,
prop3: firstName + ' ' + lastName + ' says Hello world!'
}
return a;
};
// Now, let's use our factory to produce new objects
// let's actually have an example to treat it like real life factories :P
var inputArr = [
{firstName: 'Barack', lastName: 'Obama'},
{firstName: 'Narendra', lastName: 'Modi'},
{firstName: 'Mike', lastName: 'Tyson'},
{firstName: 'Mahatma', lastName: 'Gandhi'},
{firstName: 'Donald', lastName: 'Trump'},
{firstName: 'Priyanka', lastName: 'Chopra'}
];
var outputArr = [];
inputArr.forEach(function (x) {
var newObj = ourFactoryFn(x.firstName, x.lastName); // we used our factory
console.dir(newObj); // print the freshly created object
outputArr.push(newObj);
});
Aucun commentaire:
Enregistrer un commentaire