V
V
VzzzzZZ2020-04-15 17:26:44
JavaScript
VzzzzZZ, 2020-04-15 17:26:44

How to specify the behavior of an object when using the Factory pattern instead of Classes?

Let's say I use the following code to create a newCar object:

const vehicleFactory = function (config) {

    const MoveBehaivor = {
        move(){
            console.log('move')
        }
    }

    const vehicle = Object.assign({},MoveBehaivor)

    return vehicle 
}

let newCar = vehicleFactory()
newCar.move()	// 'move'


Everything is simple here - we set the behavior, create an object (if necessary, then with the parameters from the config) and return

Now we make a change to the factory so that we start producing tanks.
At the same time, we need the newly created tank object to have the same .move() method, but at the same time more specialized (refined).
You can introduce a TankMoveBehaivor object with a completely overridden move() method and use it:
const vehicleFactory = function (config) {

    const MoveBehaivor = {
        move(){
            console.log('move')
        }
    }

    const TankMoveBehaivor = {
        move(){
            console.log('move')
            console.log('as tank')	// отличие от метода для автомобилей
        }
    }

    switch (config.type) {
        case 'car' :

        const car = Object.assign({},MoveBehaivor)
    
        return car
    
        case  'tank' :

        const vehicle = Object.assign({},TankMoveBehaivor)

        return vehicle
    }
}


But if the move() method is large and complex, then duplicating it will result in a lot of repetitive code, which of course we would like to avoid

Using class notation, we could create a class Vehicle from which class Car and class Tank would inherit the move() method,
refining it when need.

How to do the same using only the above pattern?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question