instance factory methods Vs Static factory methods

前端 未结 5 848
难免孤独
难免孤独 2020-12-23 11:35

Can\'t all factory methods be static ? Does something that produces a product need state ? When is it appropriate to go for a instance factory or static factory method ? Ca

5条回答
  •  旧巷少年郎
    2020-12-23 12:10

    It depends, for instance you can have a factory that will only produce a certain amount of objects in which case there will be an associated state. For the most part factory methods can be static as long as they don't rely on any non-static variables (such as non-static globals and such) for their creation. It also tends to differentiate different factories for different parts of an application so depending on whether there is a state or not in your factory is what you would go with it's not set in stone that all factory methods should be static, check what situation applies to you and write it appropriately.

    Another consideration is the static keyword, this causes whatever is static to be instantiated only once in memory but a drawback is that it resides in the process memory always (which increases working set size). This may be something that you don't want as your factory might have very high locality in certain areas and it would otherwise just be using up memory somewhere else but this is usually an optimization issue that should be looked at only if the issue of memory pressure in your application arises.

提交回复
热议问题