How to name factory like methods?

后端 未结 11 1896
别跟我提以往
别跟我提以往 2021-01-29 19:41

I guess that most factory-like methods start with create. But why are they called \"create\"? Why not \"make\", \"produce\", \"build\", \"generate\" or something el

11条回答
  •  一向
    一向 (楼主)
    2021-01-29 20:37

    Joshua Bloch in "Effective Java" suggests the following naming conventions

    valueOf — Returns an instance that has, loosely speaking, the same value as its parameters. Such static factories are effectively type-conversion methods.

    of — A concise alternative to valueOf, popularized by EnumSet (Item 32).

    getInstance — Returns an instance that is described by the parameters but cannot be said to have the same value. In the case of a singleton, getInstance takes no parameters and returns the sole instance.

    newInstance — Like getInstance, except that newInstance guarantees that each instance returned is distinct from all others.

    getType — Like getInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.

    newType — Like newInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.

提交回复
热议问题