I have some questions on the Factory pattern, I'll try to illustrate them using the example of handling HTTP errors in JS.
As far as I know, a "proper" factory would instance different ErrorXXX classes depending on the arguments passed to the Factory, like so:
class HTTPError {
createError(code) {
if (code === 'NOT_FOUND') {
return new Error404()
} else if (code === 'NOT_AUTH') {
return new Error401()
}
// etc....
}
}
But since in this example all of the classes will have the same properties you could have the conditional assigning values to those properties in a single class, instead of instantiating many different classes
class HTTPError {
createError(code) {
let status = 500
let message = 'Server error'
if (code === 'NOT_FOUND') {
status = 404
message = 'Page not found'
} else if (code === 'NOT_AUTH') {
status = 401
message = 'Resource not authorized'
}
// etc...
return {status, message}
}
}
My questions are:
- What are the different purposes of these two patterns?
- Which one would be better suited for the task in the example?
- Does the second pattern have a name?
Aucun commentaire:
Enregistrer un commentaire