public static factory method

后端 未结 5 405
灰色年华
灰色年华 2020-12-29 07:08

First of all please forgive me if its a really dumb question, I am just trying to learn this language to its core. I am reading Effective Java and the very first chapter tal

5条回答
  •  一个人的身影
    2020-12-29 07:44

    class of an object returned by static factory method is nonpublic

    Frequently a static factory method will return either an an object typed as an interface (most common), or sometimes some base class (less common). In either case, you don't know the exact class of the returned object.

    The advantage of this is getting an object whose behaviour you know without worrying about the messy details of what class it instantiates.

    unlike constructors static factory methods are not required to create a new object each time they are invoked

    To understand this, consider the case of working with a singleton. You may call .getInstance() on some factory classes to get the singleton instance of an certain object. Typically, what this does is create an instance of the object if it doesn't already exist, or give you the existing instance if it already does. In either case, you get back a copy of the object. But you don't (and won't) know if this singleton had to be created, or if one had already been constructed previously.

    The advantage of this is that the lifecycle of the object and when it is created is managed for you.

提交回复
热议问题