new object is created or not?

北慕城南 提交于 2019-12-12 05:00:20

问题


I am reading Effective Java by Joshua Bloch. It confuses me in the item 1, where it states

A second advantage of static factory method is that, unlike constructors, they are not required to create a new object each time time they're invoked.

Isn't the static factory method meant to create a new object each time it is invoked?

//constructor
Orange(){
}

//static factory method
static Orange staticFactoryMethod(){
    return new Orange;
}

Won't calling either the constructor or the staticFactoryMethod create an instance of Orange?

Orange orange=new Orange();

Orange orange=Orange.staticFactoryMethod();

回答1:


A static factory does not always need to create a new object. You can have this:

static Orange staticFactoryMethod(){
    return new Orange();
}

But you can also have something like

static Orange staticFactoryMethod(){
    Orange o = ... //find an orange in a basket of available oranges that has been already initialized
    return o;
}



回答2:


Take a look at Integer.valueOf(int i). If i is within the range -128 to 127 this method will not create a new Integer object but return a value from cache.




回答3:


Isn't the static factory method is mean to create a new object each time it is invoked?

No. The purpose of a factory method is to return a suitable object. That object might be an object that was created earlier. It all depends on the intended semantics of the factory, and of the objects. For instance, it the objects are immutable and their object identity has no special significance, then sharing instances can be a worthwhile optimization.

For example, the Integer.valueOf(int) method returns an Integer method that may (for small integers) have been created and used previously. This has the advantage of reducing the number of Integer instances that are created ... and need to be garbage collected when they are finished with.

You could also argued that String.intern(String) is a form of factory method, though it has the unusual property that (in recent implementations) it never allocates new strings.

A third example is a thread or connection pool which tries to recycle objects that have been returned to the pool.

By contrast, if the "client" of your API has to use new to create instances, there is no opportunity for your API to do this kind of thing. That is Bloch's point.



来源:https://stackoverflow.com/questions/16620832/new-object-is-created-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!