samedi 30 mai 2020

Why is a Factory Design Pattern recommended? (over simply using an object in JS)

Currently learning about design patterns in JavaScript in this course, I began questioning the use-case of the Factory Design Pattern.

For example, the following is some code that's a Factory Design Pattern for repositories:

const util = require('util')

const Repos = function() {
    // We are creating a copy of this function constructor (not sure what that means).
    let repos = this
    console.log('before' + util.inspect(this, {showHidden: false, depth: null}))

    let repoList = [
        {name: 'Task', source: './taskRepository'},
        {name: 'Project', source: './projectRepository'},
        {name: 'User', source: './userRepository'},
    ]

    for (const repo of repoList){
        repos[repo.name] = require(repo.source)()
    }

    console.log('after' + util.inspect(this, {showHidden: false, depth: null}))
}

While it's nice and clean code, I am questioning, why cannot we just an object, like the following:

const RepoObject2 = {
    Task: require('./taskRepository')(),
    Project: require('./projectRepository')(),
    User: require('./userRepository')(),
}

Appreciate any responses, thanks!

Aucun commentaire:

Enregistrer un commentaire