In simplest terms, what is a factory?

后端 未结 6 1532
南方客
南方客 2020-11-30 05:57

What is a factory and why would I want to use one?

6条回答
  •  没有蜡笔的小新
    2020-11-30 06:11

    The factory is an object, that creates objects. The common usage includes two cases:

    • When you want to delegate the choice of the concrete object to the factory - e.g. it may return an already existing object (see Integer.valueOf(), which is a so-called factory method) or choose a concrete implementation depending on some conditions - e.g. supplied argument or pre-defined options (see XPathFactory class in Java API for XML Processing)
    • When you want more flexibility for some universal job. You cannot pass a method or a constructor as an argument (well, you can, but reflection sucks), so you use a concrete factory as an object source (e.g. SomeFactory in a generic method).

提交回复
热议问题