I want to use factory design pattern in my application and use of some of its benefits such as readability, flexibility, scalability, encapsulation and correct binding of "this" operator" during development. As my application generates html code in loading of my webpage, the performance and memory usage of creating objects is important in my case. Please take a look at the following example;
// Factory Design with Delegation
const car = function( color )
{
const CarPrototype = function( color )
{
const carPrototype = {};
carPrototype.color = color;
// Private function
function internal()
{
console.log( "internal" );
// ...
}
// Public function
carPrototype.gas = function()
{
internal();
// ...
}
carPrototype.brake = function()
{
// ...
}
return carPrototype;
}
return Object.create( CarPrototype( color ) );
}
// Traditional constructor function
const Car = function( color )
{
this.color = color;
// ...
}
Car.prototype.internal = function()
{
console.log( "internal" );
// ...
}
Car.prototype.gas = function()
{
this.internal();
// ...
}
Car.prototype.brake = function()
{
// ...
}
function myFunction()
{
const mazdaF = car( "red" );
const mazdaT = new Car( "red" );
console.log( mazdaF, mazdaT );
}
<html>
<head></head>
<body onload="myFunction()">
</body>
</html>
The result of running the above code is shown below.
In addition, performance test result is shown here Performance result.
I want to know whether I am using a correct pattern for my case or not. In case, what should I do to improve performance?
UPDATE:
Now I am a little confused about the factory pattern above. I think when I use Object.create( CarPrototype( color ) )
, I am creating a totally new car object and return an object which its prototype linked to that car object. So if I create 1000 car objects, I will have 1000 car prototypes instead of one prototype with 1000 delegation links. Am I right? If this is true, can anybody explain me how to correct it?