When to use Factory method pattern?

后端 未结 10 1452
南旧
南旧 2020-12-12 14:56

When to use Factory method pattern?

Please provide me some specific idea when to use it in project? and how it is a better way over new keyword?

10条回答
  •  攒了一身酷
    2020-12-12 15:50

    You can refer to section 9.5 Factories from Framework Design Guidelines 2nd Edition. Here is quoted set of guidelines with respect to using factories over constructors:

    DO prefer constructors to factories, because they are generally more usable, consistent, and convenient than specialized construction mechanisms.

    CONSIDER using a factory if you need more control than can be provided by constructors over the creation of the instances.

    DO use a factory in cases where a developer might not know which type to construct, such as when coding against a base type or interface.

    CONSIDER using a factory if having a named method is the only way to make the operation self-explanatory.

    DO use a factory for conversion-style operations.

    And from section 5.3 Constructor Design

    CONSIDER using a static factory method instead of a constructor if the semantics of the desired operation do not map directly to the construc- tion of a new instance, or if following the constructor design guidelines feels unnatural.

提交回复
热议问题