Constructor function vs Factory functions

后端 未结 7 855
清酒与你
清酒与你 2020-11-22 06:52

Can someone clarify the difference between a constructor function and a factory function in Javascript.

When to use one instead of the other?

7条回答
  •  旧巷少年郎
    2020-11-22 06:59

    Factories are "always" better. When using object orientated languages then

    1. decide on the contract (the methods and what they will do)
    2. Create interfaces that expose those methods (in javascript you don't have interfaces so you need to come up with some way of checking the implementation)
    3. Create a factory that returns an implementation of each interface required.

    The implementations (the actual objects created with new) are not exposed to the factory user/consumer. This means that the factory developer can expand and create new implementations as long as he/she doesn't break the contract...and it allows for the factory consumer to just benefit from the new API without having to change their code...if they used new and a "new" implementation comes along then they have to go and change every line which uses "new" to use the "new" implementation...with the factory their code doesn't change...

    Factories - better than all anything else - the spring framework is completely built around this idea.

提交回复
热议问题