What are static factory methods?

前端 未结 14 1081
粉色の甜心
粉色の甜心 2020-11-22 06:08

What\'s a \"static factory\" method?

14条回答
  •  温柔的废话
    2020-11-22 06:43

    A factory method a method that abstracts away the instantiation of an object. Generally factories are useful when you know that you need a new instance of a class that implements some interface but you don't know the implementing class.

    This is useful when working with hierarchies of related classes, a good example of this would be a GUI toolkit. You could simply hard-code calls to the constructors for concrete implementations of each widget but if you ever wanted to swap one toolkit for another you'd have a lot of places to change. By using a factory you reduce the amount of code you would need to change.

提交回复
热议问题