简体   繁体   中英

new object is created or not?

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();

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;
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM