【问题标题】:The Factory Pattern Equivalent of the Constructor Pattern构造函数模式的工厂模式等价物
【发布时间】:2019-02-23 00:47:56
【问题描述】:

我正在使用构造函数模式来创建我的对象,如下所示;

// 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 );
    // ...
}

我想将我的设计更改为与此设计相同但具有工厂功能的设计。于是我写了如下代码;

// 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 } 
    } );
}

最后,我按如下方式创建对象;

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

我想知道这是否正确。如果这不是真的,任何人都可以帮助我以最佳方式实现它吗?

【问题讨论】:

  • 好的,把代码粘贴到某个地方运行一下,好像可以用,没有什么特别的不足。

标签: javascript design-patterns constructor factory-pattern


【解决方案1】:

这似乎对我很有效。它与我使用的语法不同。行为的一个关键区别是您的工厂允许我查看内部范围。我可以使用 mazdaF.colormazdaF.config 访问颜色和配置。如果您希望它以这种方式工作,那很好。但是,如果您希望内部范围对对象是私有的,您将使用不同的语法。

这是另一种方式(我不确定这是通用的标准做法,所以我希望其他人能加入...):

const carFactory2=(c,s,o)=>{
    const color=c;
    const config={'speed':s, 'oil':o};
    const internal=()=>{
        console.log('internal');
    }
    return{
        gas: ()=>{
            internal();
            return color;
        },
        brake: ()=>{
            internal();
        }
    }
}

var mazdaF = carFactory2( "red", 10, 130 );

这种方式实际上使一个对象保留了函数的内部范围。 colorconfiginternal() 在函数外部无法访问,因此无法在下游更改,除非您为其添加方法。在这里,mazdaF.gas() 将返回颜色并执行内部方法。 ...但是 config 也不能通过调用 mazdaF.brake() OR 蛮力来更改 mazdaF.config = ...

我希望我不会造成混乱。同样,我认为您的选择将取决于您希望如何使用内部范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    相关资源
    最近更新 更多