Java 'Prototype' pattern - new vs clone vs class.newInstance

前端 未结 6 992
别那么骄傲
别那么骄傲 2021-02-08 18:11

In my project there are some \'Prototype\' factories that create instances by cloning a final private instance.

The author of those factories says that this pattern prov

6条回答
  •  执念已碎
    2021-02-08 18:53

    As others have said this is an antiquated practice. It is an outdated pattern that unfortunately with the newer JVMs will add more bloat to the code without giving a performance boost.

    I wish I still had the code so I could share, but a while back I did a simple performance test of this pattern vs using the 'new' operator and I found that using the 'new' operator was at worst at least as fast as this pattern, and at best faster and more efficient. There may be some edge case my test didn't cover where this could still be a valid approach, but in general I would say avoid this pattern.

    Another note though, I would suggest you not worry about this too much if it is present in an existing code base. But also I wouldn't write new code to extend this pattern for more parts of your project, unless not doing so would hurt the clarity and consistency of your code base- at which point you should evaluate whether or not it would be smart in the long run to refactor this code out of your project. By 'smart' I mean, would refactoring this code out of your project save time in the future on development and debugging > the amount of time necessary to refactor this out.

提交回复
热议问题