mardi 18 septembre 2018

The Factory Pattern Equivalent of the Constructor Pattern

I am using the constructor pattern for creating my objects like below;

// Traditional constructor function
const Car = function( color, speed, oil )
{
    this.color = color;
    this.config = { speed: speed, oil: oil };
    // ...
}

Car.prototype.internal = function()
{
    console.log( "internal" );
    // ...
}

Car.prototype.gas = function()
{
    this.internal();
    console.log( this.color );
    // ...
}

Car.prototype.brake = function()
{
    console.log( this.config );
    // ...
}

And I want to change my design to an equivalent of this design but with factory functions. So I wrote the following code;

// Factory Design with Delegation
const carProto = ( function()
{
    const carPrototype = {};
    // Private function
    function internal()
    {
        console.log( "internal" );
        // ...
    }

    // Public function
    carPrototype.gas = function()
    {
        internal();
        console.log( this.color );
        // ...
    }

    carPrototype.brake = function()
    {
        console.log( this.config );
        // ...
    }

    return carPrototype;
} )();

function carFactory( color, speed, oil ) 
{
    return Object.assign( Object.create( carProto ), 
    { 
        color: color,
        config: { speed: speed, oil: oil } 
    } );
}

Finally, I create my objects as follows;

var mazdaF = carFactory( "red", 10, 130 );
var mazdaT = new Car( "yellow", 20, 120 );

I want to know whether this is correct or not. If this is not true, can anybody help me with the best way to implement that?

Aucun commentaire:

Enregistrer un commentaire